
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 { Badge } from "@/components/ui/badge";
import { Search, Plus } from "lucide-react";
import { authFetch } from '@/lib/api';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import UserModal from './UserModal';


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

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

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

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

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

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

  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">Pharmacies</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 pharmacies..."
              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 Pharmacy
          </Button> */}
        </div>
      </div>

      <div className="rounded-md border border-gray-200">
        <Table>
          <TableHeader>
            <TableRow className="border-gray-200">
              <TableHead>Name</TableHead>
              <TableHead className="hidden md:table-cell">Location</TableHead>
              {/* <TableHead className="hidden md:table-cell">Inventory Items</TableHead> */}
              <TableHead>Verification Document</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {pharmaciesList.map((pharmacy) => (
              <TableRow key={pharmacy.id} className="border-gray-200">
                <TableCell>
                  <div className="flex items-center">
                    <span className="font-medium">{pharmacy.name}</span>
                  </div>
                </TableCell>
                <TableCell className="hidden md:table-cell">{pharmacy.address}</TableCell>
                {/* <TableCell className="hidden md:table-cell">{pharmacy.inventory}</TableCell> */}
                <TableCell className="hidden md:table-cell">
                  {pharmacy.verificationDocuments ? (
                    <a href={pharmacy.verificationDocuments} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
                      View Document
                    </a>
                  ) : (
                    <span className="text-gray-500">No Document</span>
                  )}
                </TableCell>
                <TableCell>
                  <Badge
                    variant="outline"
                    className={
                      pharmacy.isVerified
                        ? "border-green-400 text-green-400"
                        : "border-red-400 text-red-400"
                    }
                  >
                    {pharmacy.isVerified ? 'Verified' : 'Unverified'}
                  </Badge>
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-1 flex-wrap">
                    <Button
                      onClick={() => setSelectedUser(pharmacy)}
                      className="bg-blue-500 text-white px-2 py-1 rounded hover:bg-blue-600 text-xs"
                    >
                      View
                    </Button>
                    {!pharmacy.isVerified && (
                      <Button
                        onClick={() => handleVerify(pharmacy.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 Pharmacies;
