import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import React, { useState } from 'react';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Search, Plus, FileText, GraduationCap, Siren } from "lucide-react";
import { authFetch } from '@/lib/api';
import UserModal from './UserModal';

const getAvatarUrl = (avatarPath) => {
    if (!avatarPath) return '/images/patient1.jpg';
    if (avatarPath.startsWith('http')) return avatarPath;
    return `${process.env.NEXT_PUBLIC_BACKEND_URL}${avatarPath}`;
};

async function fetchDoctors(searchTerm = '') {
    const url = searchTerm
        ? `/api/admin/doctors?search=${encodeURIComponent(searchTerm)}`
        : '/api/admin/doctors';
    return authFetch(url);
}

const Doctors = () => {
    const queryClient = useQueryClient();
    const [selectedUser, setSelectedUser] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedDoctor, setSelectedDoctor] = useState(null);
    const [viewDocument, setViewDocument] = useState(null);

    const { data: doctors = [], isLoading, isError } = useQuery({
        queryKey: ['doctors', searchTerm],
        queryFn: () => fetchDoctors(searchTerm),
    });

    const verifyMutation = useMutation({
        mutationFn: (doctorId) =>
            authFetch(`/api/admin/doctors/${doctorId}/verify`, {
                method: 'PUT',
            }),
        onSuccess: () => {
            // Invalidate and refetch labs data
            queryClient.invalidateQueries(['doctors']);
        }
    });

    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
    };

    const handleVerify = async (doctorId) => {
        try {
            await verifyMutation.mutateAsync(doctorId);
        } catch (error) {
            console.error('Error verifying doctor:', error);
            alert('Failed to verify doctor. Please try again.');
        }
    };

    if (isError) {
        return (
            <div className="space-y-6 px-4 sm:px-6 lg:px-8">
                <div className="flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-center">
                    <h1 className="text-2xl font-bold tracking-tight">Doctors</h1>
                    <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                        <div className="relative w-full sm:w-64">
                            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-[#64758a]" />
                            <Input
                                type="search"
                                placeholder="Search doctors..."
                                className="w-full pl-8 border-gray-200"
                                value={searchTerm}
                                onChange={handleSearch}
                            />
                        </div>
                        <Button className="bg-blue-500 text-white hover:bg-blue-400 w-full sm:w-auto">
                            <Plus className="mr-2 h-4 w-4" /> Add Doctor
                        </Button>
                    </div>
                </div>
                <div className="rounded-md border border-gray-200 p-4 text-red-500">
                    Failed to load doctors. Please try again.
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6 px-4 sm:px-6 lg:px-8">
            {/* Header Section */}
            <div className="flex flex-col gap-4 sm:flex-row sm:justify-between sm:items-center">
                <h1 className="text-2xl font-bold tracking-tight">Doctors</h1>
                <div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                    <div className="relative w-full sm:w-64">
                        <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-[#64758a]" />
                        <Input
                            type="search"
                            placeholder="Search doctors..."
                            className="w-full pl-8 border-gray-200"
                            value={searchTerm}
                            onChange={handleSearch}
                        />
                    </div>
                    {/* <Button className="bg-blue-500 text-white hover:bg-blue-400 w-full sm:w-auto">
                        <Plus className="mr-2 h-4 w-4" /> Add Doctor
                    </Button> */}
                </div>
            </div>

            {/* Table Section */}
            <div className="rounded-md border border-gray-200 overflow-x-auto">
                <Table>
                    <TableHeader>
                        <TableRow className="border-gray-200">
                            <TableHead className="w-[200px]">Name</TableHead>
                            <TableHead>Licence Number</TableHead>
                            <TableHead>Speciality</TableHead>
                            <TableHead className="hidden lg:table-cell">Patients</TableHead>
                            <TableHead className="text-center hidden md:table-cell">Documents</TableHead>
                            <TableHead className="text-center hidden sm:table-cell">is Verified</TableHead>
                            <TableHead className="hidden sm:table-cell">Status</TableHead>
                            <TableHead className="text-right w-[150px]">Actions</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {doctors.map((doctor) => (
                            <TableRow key={doctor.id} className="border-gray-200">
                                <TableCell>
                                    <div className="flex items-center gap-3">
                                        <Avatar>
                                            <AvatarImage src={getAvatarUrl(doctor.avatar)} alt={doctor.firstName} />
                                            <AvatarFallback>{doctor.name.charAt(0)}</AvatarFallback>
                                        </Avatar>
                                        <span className="font-medium text-sm sm:text-base">{doctor.name}</span>
                                    </div>
                                </TableCell>
                                <TableCell className="text-sm sm:text-base">{doctor.licenceNumber}</TableCell>
                                <TableCell className="text-sm sm:text-base">{doctor.speciality}</TableCell>
                                <TableCell className="hidden lg:table-cell">{doctor.patients}</TableCell>
                                <TableCell className="text-center hidden md:table-cell">
                                    <div className="flex justify-center gap-1 flex-wrap">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-xs p-1"
                                            onClick={() => {
                                                setSelectedDoctor(doctor);
                                                setViewDocument('cv');
                                            }}
                                            disabled={!doctor.cvUrl}
                                        >
                                            <FileText className="h-4 w-4 mr-1" />
                                            CV
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-xs p-1"
                                            onClick={() => {
                                                setSelectedDoctor(doctor);
                                                setViewDocument('degree');
                                            }}
                                            disabled={!doctor.degreeCertificateUrl}
                                        >
                                            <GraduationCap className="h-4 w-4 mr-1" />
                                            Degree
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-xs p-1"
                                            onClick={() => {
                                                setSelectedDoctor(doctor);
                                                setViewDocument('backgroundcheck');
                                            }}
                                            disabled={!doctor.backgroundCheckUrl}
                                        >
                                            <Siren className="h-4 w-4 mr-1" />
                                            Police Check
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-xs p-1"
                                            onClick={() => {
                                                setSelectedDoctor(doctor);
                                                setViewDocument('workreference');
                                            }}
                                            disabled={!doctor.workReference}
                                        >
                                            <FileText className="h-4 w-4 mr-1" />
                                            Work Reference
                                        </Button>
                                    </div>
                                </TableCell>
                                <TableCell className="text-center hidden sm:table-cell">
                                    <Badge
                                        variant={doctor.isVerified ? "success" : "outline"}
                                        className={doctor.isVerified ? "border-green-400 text-green-400" : "border-red-400 text-red-400"}
                                    >
                                        {doctor.isVerified ? "Yes" : "No"}
                                    </Badge>
                                </TableCell>
                                <TableCell className="hidden sm:table-cell">
                                    <Badge
                                        variant="outline"
                                        className={
                                            doctor.status === "Active"
                                                ? "border-green-400 text-green-400"
                                                : "border-orange-400 text-orange-400"
                                        }
                                    >
                                        {doctor.status}
                                    </Badge>
                                </TableCell>
                                <TableCell className="text-right">
                                    <div className="flex justify-end gap-1 flex-wrap">
                                        <Button
                                            onClick={() => setSelectedUser(doctor)}
                                            className="bg-blue-500 text-white px-2 py-1 rounded hover:bg-blue-600 text-xs cursor-pointer"
                                        >
                                            View
                                        </Button>
                                        {!doctor.isVerified && (
                                            <Button
                                                onClick={() => handleVerify(doctor.id)}
                                                disabled={verifyMutation.isLoading}
                                                className="bg-green-500 text-white px-2 py-1 rounded hover:bg-green-600 text-xs cursor-pointer"
                                            >
                                                {verifyMutation.isLoading ? 'Verifying...' : 'Verify'}
                                            </Button>
                                        )}
                                    </div>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </div>

            {/* Modal for User Details */}
            {selectedUser && (
                <UserModal user={selectedUser} onClose={() => setSelectedUser(null)} />
            )}

            {/* Document Viewer Dialog */}
            <Dialog
                open={!!viewDocument}
                onOpenChange={(open) => !open && setViewDocument(null)}
            >
                <DialogContent className="w-[95vw] sm:max-w-4xl h-[80vh] max-w-full p-0 bg-white">
                    <DialogHeader className="px-6 pt-6 pb-2">
                        <DialogTitle>
                            {selectedDoctor?.name}&apos;s {viewDocument === 'cv' ? 'CV' : viewDocument === 'degree' ? 'Degree Certificate' : 'Police Check'}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="flex-1 p-6 pt-0">
                        {viewDocument && selectedDoctor && (
                            <iframe
                                src={
                                    viewDocument === 'cv'
                                        ? selectedDoctor.cvUrl
                                        : viewDocument === 'degree'
                                            ? selectedDoctor.degreeCertificateUrl
                                            : viewDocument === 'workreference'
                                                ? selectedDoctor.workReference
                                                : selectedDoctor.backgroundCheckUrl
                                }
                                className="w-full h-full border rounded-md"
                                style={{ minHeight: 'calc(80vh - 100px)' }}
                                title={`${selectedDoctor.name}'s ${viewDocument === 'cv' ? 'CV' : viewDocument === 'degree' ? 'Degree Certificate' : viewDocument === 'backgroundcheck' ? 'Police Check' : 'Work Reference'}`}
                            />
                        )}
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
};

export default Doctors;