'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from "@/components/ui/button";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
// import { toast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";
import { authFetch } from '@/lib/api';

export function UpdateStatusForm({ prescriptionId, currentStatus, onStatusUpdated }) {
    const [status, setStatus] = useState(currentStatus);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const router = useRouter();

    const handleSubmit = async () => {
        setIsSubmitting(true);
        try {
            const res = await authFetch(`/api/pharmacies/prescriptions/${prescriptionId}/status`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ status }),
            });

            // if (!res.ok) throw new Error('Failed to update status');

            // toast({
            //     title: "Status updated",
            //     description: "Prescription status has been updated successfully.",
            // });

            // Call the callback to trigger UI update
            onStatusUpdated();

            // Optional: Refresh the page to ensure all data is fresh
            router.refresh();
        } catch (error) {
            // toast({
            //     title: "Error",
            //     description: error.message,
            //     variant: "destructive",
            // });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="space-y-4">
            <Select value={status} onValueChange={setStatus}>
                <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent className="bg-white">
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="ready">Ready</SelectItem>
                    <SelectItem value="fulfilled">Fulfilled</SelectItem>
                    <SelectItem value="rejected">Rejected</SelectItem>
                </SelectContent>
            </Select>

            <Button
                onClick={handleSubmit}
                disabled={isSubmitting || status === currentStatus}
                className="w-full bg-blue-500 text-white cursor-pointer"
            >
                {isSubmitting ? (
                    <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Updating...
                    </>
                ) : 'Update Status'}
            </Button>
        </div>
    );
}