import { useState, useEffect } from "react";
import axios from "axios";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogTrigger,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
    DialogClose,
} from "@/components/ui/dialog";
import { X } from "lucide-react";
import {
    Select,
    SelectTrigger,
    SelectValue,
    SelectContent,
    SelectItem,
} from "@/components/ui/select";
import { authFetch } from "@/lib/api";
import { useAuthStore } from '@/stores/authStore';
import { toast } from "@/hooks/useToast";

const PrescriptionModal = ({ consultationId, patientId, patientName, children }) => {
    const [medicines, setMedicines] = useState([
        { name: "", dosage: "", duration: "" },
    ]);
    const [isOpen, setIsOpen] = useState(false);
    const [pharmacies, setPharmacies] = useState([]);
    const [selectedPharmacy, setSelectedPharmacy] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const user = useAuthStore((state) => state.user);

    useEffect(() => {
        if (isOpen) {
            const fetchPharmacies = async () => {
                try {
                    const res = await authFetch("/api/pharmacies");
                    setPharmacies(res);
                } catch (err) {
                    console.error("Failed to fetch pharmacies", err);
                }
            };
            fetchPharmacies();
        }
    }, [isOpen]);

    // Add a new medicine field
    const addMedicine = () => {
        setMedicines([...medicines, { name: "", dosage: "", duration: "" }]);
    };

    // Update a specific medicine field
    const handleMedicineChange = (index, field, value) => {
        const updatedMedicines = [...medicines];
        updatedMedicines[index][field] = value;
        setMedicines(updatedMedicines);
    };

    // Remove a medicine field
    const removeMedicine = (index) => {
        const updatedMedicines = medicines.filter((_, i) => i !== index);
        setMedicines(updatedMedicines);
    };

    // Submit prescription to backend
    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await authFetch(
                "/api/prescriptions",
                {
                    method: "POST",
                    body: JSON.stringify({
                        patientId,
                        doctorId: user.id, // Assuming userId is stored in localStorage
                        pharmacyId: selectedPharmacy,
                        medicines,
                        consultationId
                    }),
                }
            );
            toast("Prescription submitted successfully!");
            setMedicines([{ name: "", dosage: "", duration: "" },])
            setSelectedPharmacy("");
            setIsOpen(false);
        } catch (err) {
            alert("Error submitting prescription: " + err.message);
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogTrigger asChild>
                {children || <Button variant="outline">Create Prescription</Button>}
            </DialogTrigger>
            <DialogContent className="sm:max-w-[600px] bg-gray-50">
                <DialogHeader>
                    <DialogTitle>Create E-Prescription</DialogTitle>
                    <DialogDescription>
                        Add medicines and select a pharmacy for {patientName}. Click &quot;Add Medicine&quot; to include more.
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={handleSubmit}>
                    <div className="mb-6">
                        <label className="block text-sm font-medium mb-2">
                            Select Pharmacy
                        </label>
                        <Select
                            value={selectedPharmacy}
                            onValueChange={setSelectedPharmacy}
                            required
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Select a pharmacy..." />
                            </SelectTrigger>
                            <SelectContent className="bg-white hover:bg-gray-100">
                                {pharmacies?.map((pharmacy) => (
                                    <SelectItem key={pharmacy.id} value={pharmacy.userId} className=" bg-white hover:bg-gray-100 cursor-pointer">
                                        {pharmacy.pharmacyName} - {pharmacy.address}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    <div className="grid gap-4 py-4">
                        {medicines.map((med, index) => (
                            <div
                                key={index}
                                className="grid grid-cols-12 items-center gap-4"
                            >
                                <div className="col-span-5">
                                    <label htmlFor={`name-${index}`} className="sr-only">
                                        Medicine Name
                                    </label>
                                    <input
                                        id={`name-${index}`}
                                        type="text"
                                        placeholder="Medicine name"
                                        value={med.name}
                                        onChange={(e) =>
                                            handleMedicineChange(index, "name", e.target.value)
                                        }
                                        className="w-full p-2 border rounded"
                                        required
                                    />
                                </div>
                                <div className="col-span-4">
                                    <label htmlFor={`dosage-${index}`} className="sr-only">
                                        Dosage
                                    </label>
                                    <input
                                        id={`dosage-${index}`}
                                        type="text"
                                        placeholder="Dosage (e.g., 500mg)"
                                        value={med.dosage}
                                        onChange={(e) =>
                                            handleMedicineChange(index, "dosage", e.target.value)
                                        }
                                        className="w-full p-2 border rounded"
                                        required
                                    />
                                </div>
                                <div className="col-span-2">
                                    <label htmlFor={`duration-${index}`} className="sr-only">
                                        Duration
                                    </label>
                                    <input
                                        id={`duration-${index}`}
                                        type="text"
                                        placeholder="Duration"
                                        value={med.duration}
                                        onChange={(e) =>
                                            handleMedicineChange(index, "duration", e.target.value)
                                        }
                                        className="w-full p-2 border rounded"
                                    />
                                </div>
                                <div className="col-span-1">
                                    <button
                                        type="button"
                                        onClick={() => removeMedicine(index)}
                                        className="text-red-500 hover:text-red-700"
                                    >
                                        <X className="h-4 w-4" />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>

                    <Button
                        type="button"
                        variant="secondary"
                        size="sm"
                        onClick={addMedicine}
                        className="mt-2"
                    >
                        Add Medicine
                    </Button>

                    <DialogFooter className="mt-6">
                        <DialogClose asChild>
                            <Button type="button" variant="outline">
                                Cancel
                            </Button>
                        </DialogClose>
                        <Button type="submit" className="cursor-pointer">Submit Prescription</Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
};

export default PrescriptionModal;