"use client"
import { use } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { notFound, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ClipboardList, Clock, CheckCircle2, AlertCircle, User, Pill, Loader2 } from "lucide-react";
import { authFetch } from "@/lib/api";
import { UpdateStatusForm } from "@/components/UpdateStatusForm";

async function fetchPrescription(id) {
    return authFetch(`/api/pharmacies/prescriptions/${id}`);
}

export default function PrescriptionPage({ params }) {
    const router = useRouter();
    const queryClient = useQueryClient();
    const unwrappedParams = use(params);
    const id = unwrappedParams.id;

    const { data: prescription, isLoading, isError } = useQuery({
        queryKey: ['pharmacy-prescription', id],
        queryFn: () => fetchPrescription(id),
        retry: false
    });

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-64">
                <Loader2 className="h-8 w-8 animate-spin" />
            </div>
        );
    }

    if (isError) {
        console.error('Error fetching prescription:');
        router.replace('/pharmacy/prescriptions');
        return null;
    }

    if (!prescription) notFound();

    const statusBadge = {
        pending: (
            <Badge variant="outline" className="gap-1 border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100">
                <Clock className="h-3 w-3 text-amber-600" />
                Pending
            </Badge>
        ),
        ready: (
            <Badge variant="outline" className="gap-1 border-blue-300 bg-blue-50 text-blue-800 hover:bg-blue-100">
                <Clock className="h-3 w-3 text-blue-600" />
                Ready
            </Badge>
        ),
        fulfilled: (
            <Badge variant="outline" className="gap-1 border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100">
                <CheckCircle2 className="h-3 w-3 text-emerald-600" />
                Fulfilled
            </Badge>
        ),
        rejected: (
            <Badge variant="outline" className="gap-1 border-rose-300 bg-rose-50 text-rose-800 hover:bg-rose-100">
                <AlertCircle className="h-3 w-3 text-rose-600" />
                Rejected
            </Badge>
        )
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h1 className="text-2xl font-bold">Prescription Details</h1>
                <Button variant="outline" asChild>
                    <Link href="/dashboard/pharmacy/prescriptions">Back to List</Link>
                </Button>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
                {/* Prescription Overview */}
                <Card className="md:col-span-2">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <ClipboardList className="h-5 w-5" />
                            Prescription #{prescription.id.slice(0, 8)}
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                <User className="h-4 w-4 text-gray-500" />
                                <span className="font-medium">{prescription.patient.firstName}</span>
                            </div>
                            <div>
                                {statusBadge[prescription.status]}
                            </div>
                        </div>

                        <div className="space-y-2">
                            <h3 className="font-medium">Medications</h3>
                            <div className="space-y-2">
                                {prescription.medicines.map((medicine, index) => (
                                    <div key={index} className="flex items-start gap-3 p-3 border rounded-lg">
                                        <div className="p-2 bg-blue-50 rounded-full">
                                            <Pill className="h-4 w-4 text-blue-600" />
                                        </div>
                                        <div>
                                            <p className="font-medium">{medicine.name}</p>
                                            <p className="text-sm text-gray-500">{medicine.dosage}</p>
                                            {medicine.duration && (
                                                <p className="text-xs text-gray-400">Duration: {medicine.duration}</p>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {prescription.notes && (
                            <div className="space-y-2">
                                <h3 className="font-medium">Doctor&apos;s Notes</h3>
                                <p className="text-sm text-gray-700 p-3 bg-gray-50 rounded-lg">
                                    {prescription.notes}
                                </p>
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* Status Update Card */}
                <Card>
                    <CardHeader>
                        <CardTitle>Update Status</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <UpdateStatusForm
                            prescriptionId={prescription.id}
                            currentStatus={prescription.status}
                            onStatusUpdated={() => {
                                // Invalidate the query to trigger a refetch
                                queryClient.invalidateQueries(['pharmacy-prescription', id]);
                            }}
                        />
                    </CardContent>
                </Card>
            </div>
        </div>
    );
}