
import React, { useState } from 'react';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
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 } from "lucide-react";
import { authFetch } from '@/lib/api';
import { useQuery } from '@tanstack/react-query';
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 fetchPatients(searchTerm = '') {
  const url = searchTerm
    ? `/api/admin/patients?search=${encodeURIComponent(searchTerm)}`
    : '/api/admin/patients';
  return authFetch(url);
}

const Patients = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUser, setSelectedUser] = useState(null);

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

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

  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">Patients</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 patients..."
              className="w-full sm:w-[250px] pl-8 border-gray-200"
            />
          </div>
          {/* <Button className="bg-blue-500 text-white hover:bg-blue-400 cursor-pointer">
            <Plus className="mr-2 h-4 w-4" /> Add Patient
          </Button> */}
        </div>
      </div>

      <div className="rounded-md border border-gray-200">
        <Table>
          <TableHeader>
            <TableRow className="border-gray-200">
              <TableHead>Name</TableHead>
              <TableHead>Age</TableHead>
              {/* <TableHead className="hidden md:table-cell">Doctor</TableHead> */}
              <TableHead className="hidden md:table-cell">Last Visit</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {patientsList.map((patient) => (
              <TableRow key={patient.id} className="border-gray-200">
                <TableCell>
                  <div className="flex items-center gap-3">
                    <Avatar>
                      <AvatarImage src={patient.imageUrl} alt={patient.name} />
                      <AvatarFallback>{patient.name.charAt(0)}</AvatarFallback>
                    </Avatar>
                    <span className="font-medium">{patient.name}</span>
                  </div>
                </TableCell>
                <TableCell>{patient.age}</TableCell>
                {/* <TableCell className="hidden md:table-cell">{patient.doctor}</TableCell> */}
                <TableCell className="hidden md:table-cell">{patient.lastVisit}</TableCell>
                <TableCell>
                  <Badge
                    variant="outline"
                    className={
                      patient.status === "Active"
                        ? "border-green-400 text-green-400"
                        : "border-orange-400 text-orange-400"
                    }
                  >
                    {patient.status}
                  </Badge>
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-1 flex-wrap">
                    <Button
                      onClick={() => setSelectedUser(patient)}
                      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"
                      >
                        {verifyMutation.isLoading ? 'Verifying...' : 'Verify'}
                      </Button>
                    )} */}
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      {/* Modal for User Details */}
      {selectedUser && (
        <UserModal user={selectedUser} onClose={() => setSelectedUser(null)} />
      )}
    </div>
  );
};

export default Patients;
