'use client'

import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Search, Plus, Filter, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from '@/lib/utils';
import { authFetch } from '@/lib/api';
import { Skeleton } from "@/components/ui/skeleton";
import ConsultationModal from './ConsultationModal';

async function fetchConsultations() {
    const response = await authFetch('/api/admin/all-consultations');
    return response;
}

const statusBadgeColors = {
    completed: "bg-green-400",
    active: "bg-orange-400",
    scheduled: "bg-blue-400",
    pending: "bg-yellow-400",
    archived: "bg-gray-400",
    cancelled: "bg-red-400",
};

const LoadingBadge = () => (
    <Skeleton className="h-6 w-20 rounded-full" />
);

const Consultations = () => {
    const [selectedConsultation, setSelectedConsultation] = useState(null);
    const { data: consultationsList, isLoading, error } = useQuery({
        queryKey: ['consultations'],
        queryFn: fetchConsultations,
        refetchOnWindowFocus: false,
    });
    const [expandedRows, setExpandedRows] = useState(new Set());

    const toggleRow = (id) => {
        const newExpandedRows = new Set(expandedRows);
        if (newExpandedRows.has(id)) {
            newExpandedRows.delete(id);
        } else {
            newExpandedRows.add(id);
        }
        setExpandedRows(newExpandedRows);
    };

    if (isLoading) {
        return (
            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row justify-between sm:items-center space-y-2 sm:space-y-0">
                    <Skeleton className="h-8 w-48" />
                    <div className="flex gap-2">
                        <Skeleton className="h-10 w-[250px]" />
                        <Skeleton className="h-10 w-10" />
                        <Skeleton className="h-10 w-36" />
                    </div>
                </div>

                <div className="rounded-md border border-gray-200">
                    {/* Desktop Skeleton */}
                    <div className="hidden md:block">
                        <div className="grid grid-cols-6 gap-4 p-4 border-b">
                            {['Patient', 'Doctor', 'Date', 'Type', 'Status', 'Actions'].map((header) => (
                                <Skeleton key={header} className="h-6 w-24" />
                            ))}
                        </div>
                        {[...Array(5)].map((_, i) => (
                            <div key={i} className="grid grid-cols-6 gap-4 p-4 border-b">
                                <div className="flex items-center gap-3">
                                    <Skeleton className="h-10 w-10 rounded-full" />
                                    <Skeleton className="h-5 w-32" />
                                </div>
                                <Skeleton className="h-5 w-28" />
                                <Skeleton className="h-5 w-36" />
                                <Skeleton className="h-5 w-24" />
                                <LoadingBadge />
                                <div className="flex justify-end gap-2">
                                    <Skeleton className="h-8 w-12" />
                                    <Skeleton className="h-8 w-12" />
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* Mobile Skeleton */}
                    <div className="md:hidden space-y-3 p-3">
                        {[...Array(3)].map((_, i) => (
                            <div key={i} className="border rounded-lg p-3">
                                <div className="flex justify-between items-start">
                                    <div className="flex items-center gap-3">
                                        <Skeleton className="h-10 w-10 rounded-full" />
                                        <div>
                                            <Skeleton className="h-5 w-32 mb-1" />
                                            <Skeleton className="h-4 w-24" />
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <LoadingBadge />
                                        <Skeleton className="h-4 w-4 rounded" />
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        );
    }

    if (error) {
        return <div className="text-center text-red-500">Error loading consultations</div>;
    }

    return (
        <div className="space-y-6">
            <div className="flex flex-col sm:flex-row justify-between sm:items-center space-y-2 sm:space-y-0">
                <h1 className="text-2xl font-bold tracking-tight">Consultations</h1>
                <div className="flex gap-2">
                    <div className="relative">
                        <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-[#64758a]" />
                        <Input
                            type="search"
                            placeholder="Search consultations..."
                            className="w-full sm:w-[250px] pl-8 border-gray-200"
                        />
                    </div>
                    <Button variant="outline" size="icon" className="h-10 w-10">
                        <Filter className="h-4 w-4" />
                    </Button>
                    {/* <Button className="bg-blue-500 text-white hover:bg-blue-400 cursor-pointer">
                        <Plus className="mr-2 h-4 w-4" /> New Consultation
                    </Button> */}
                </div>
            </div>

            <div className="rounded-md border border-gray-200">
                {/* Desktop Table */}
                <Table className="hidden md:table">
                    <TableHeader>
                        <TableRow className="border-gray-200">
                            <TableHead>Patient</TableHead>
                            <TableHead>Doctor</TableHead>
                            <TableHead>Date & Time</TableHead>
                            <TableHead>Type</TableHead>
                            <TableHead>CallOut Status</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead className="text-right">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {consultationsList?.length > 0 ? (
                            consultationsList.map((consultation) => (
                                <TableRow key={consultation.id} className="border-gray-200">
                                    <TableCell>
                                        <div className="flex items-center gap-3">
                                            <Avatar>
                                                <AvatarImage src={consultation.imageUrl} alt={consultation.patientName} />
                                                <AvatarFallback>{consultation.patientName.charAt(0)}</AvatarFallback>
                                            </Avatar>
                                            <span className="font-medium">{consultation.patientName}</span>
                                        </div>
                                    </TableCell>
                                    <TableCell>{consultation.doctorName}</TableCell>
                                    <TableCell>{consultation.date}</TableCell>
                                    <TableCell>{consultation.type}</TableCell>
                                    <TableCell>
                                        <Badge className={cn('text-white', statusBadgeColors[consultation.callOutStatus])}>
                                            {consultation.callOutStatus}
                                        </Badge>
                                    </TableCell>
                                    <TableCell>
                                        <Badge className={cn('text-white', statusBadgeColors[consultation.status])}>
                                            {consultation.status}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <button
                                            onClick={() => setSelectedConsultation(consultation)}
                                            className="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 text-xs cursor-pointer"
                                        >
                                            View
                                        </button>
                                        {/* <Button variant="ghost" size="sm">Edit</Button> */}
                                    </TableCell>
                                </TableRow>
                            ))
                        ) : (
                            <TableRow>
                                <TableCell colSpan={6} className="text-center">
                                    No consultations found.
                                </TableCell>
                            </TableRow>
                        )}
                    </TableBody>
                </Table>

                {/* Mobile Cards */}
                <div className="md:hidden space-y-3 p-3">
                    {consultationsList?.length > 0 ? (
                        consultationsList.map((consultation) => (
                            <div key={consultation.id} className="border rounded-lg p-3">
                                <div className="flex justify-between items-start">
                                    <div className="flex items-center gap-3">
                                        <Avatar>
                                            <AvatarImage src={consultation.imageUrl} alt={consultation.patientName} />
                                            <AvatarFallback>{consultation.patientName.charAt(0)}</AvatarFallback>
                                        </Avatar>
                                        <div>
                                            <div className="font-medium">{consultation.patientName}</div>
                                            <div className="text-sm text-gray-600">{consultation.date}</div>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Badge className={cn('text-white', statusBadgeColors[consultation.status])}>
                                            {consultation.status}
                                        </Badge>
                                        <button
                                            onClick={() => toggleRow(consultation.id)}
                                            className="text-gray-500 hover:text-gray-700"
                                        >
                                            {expandedRows.has(consultation.id) ? (
                                                <ChevronUp className="h-4 w-4" />
                                            ) : (
                                                <ChevronDown className="h-4 w-4" />
                                            )}
                                        </button>
                                    </div>
                                </div>

                                {expandedRows.has(consultation.id) && (
                                    <div className="mt-3 pt-3 border-t space-y-2">
                                        <div>
                                            <span className="text-xs text-gray-500">Doctor:</span>
                                            <div className="text-sm">{consultation.doctorName}</div>
                                        </div>
                                        <div>
                                            <span className="text-xs text-gray-500">Type:</span>
                                            <div className="text-sm">{consultation.type}</div>
                                        </div>
                                        <div className="flex gap-2 pt-2">
                                            <button
                                                onClick={() => setSelectedConsultation(consultation)}
                                                className="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 text-xs cursor-pointer"
                                            >
                                                View
                                            </button>
                                            {/* <Button variant="outline" size="sm" className="w-full">Edit</Button> */}
                                        </div>
                                    </div>
                                )}
                            </div>
                        ))
                    ) : (
                        <div className="text-center p-4">No consultations found.</div>
                    )}
                </div>
            </div>
            {selectedConsultation && (
                <ConsultationModal
                    consultation={selectedConsultation}
                    onClose={() => setSelectedConsultation(null)}
                />
            )}
        </div>
    );
};

export default Consultations;