'use client';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useDebounce } from '@/hooks/use-debounce';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { Edit, Eye, Plus, Star, Trash2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import SurveyForm from '../Survey/SurveyForm';
import PatientForm from './PatientForm';
import ConfirmDialog from '@/components/common/ConfirmDialog';
import PaginationControls from '@/components/common/PaginationControls';


interface Patient {
  _id: string;
  userId: {
    _id: string;
    firstName: string;
    lastName: string;
    email: string;
    phone?: string;
  };
  gender?: string;
  dateOfBirth?: string;
  address?: string;
  medicalHistory?: string;
  createdAt: string;
}

export default function PatientList() {
  const { t, language } = useLanguage();
  const { token } = useAuthStore();
  const router = useRouter();
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  // Use a debounced value for the search term to avoid API hammering
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
  const [isSurveyDialogOpen, setIsSurveyDialogOpen] = useState(false);
  const [surveyPatientId, setSurveyPatientId] = useState<string | null>(null);
  const [pendingDeletePatient, setPendingDeletePatient] = useState<Patient | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // Pagination State
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalPatients, setTotalPatients] = useState(0);
  const [pageSize, setPageSize] = useState(10);

  // State for modal searching (separate from main list)


  const fetchPatients = useCallback(async (page: number, search: string) => {
    try {
      setLoading(true);
      if (!token) return;

      const response = await api.patients.get({
        page,
        limit: pageSize,
        search
      });

      if (response.success && response.data) {
        setPatients(response.data);
        if (response.meta) {
          setTotalPages(response.meta.totalPages);
          setTotalPatients(response.meta.total || 0);
        }
      }

    } catch (error) {
      console.error('Error fetching patients:', error);
    } finally {
      setLoading(false);
    }
  }, [token, pageSize]);

  useEffect(() => {
    fetchPatients(currentPage, debouncedSearchTerm);
  }, [currentPage, debouncedSearchTerm, fetchPatients]);

  // Reset page when search term changes (handled by debounced effect dependency)
  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearchTerm]);



  const handleDelete = (patient: Patient) => {
    setPendingDeletePatient(patient);
  };

  const confirmDelete = async () => {
    if (!pendingDeletePatient || !token) return;
    try {
      setDeleteLoading(true);
      const response = await api.patients.delete(pendingDeletePatient._id);
      if (response.success) {
        setPendingDeletePatient(null);
        fetchPatients(currentPage, debouncedSearchTerm);
      }
    } catch (error) {
      console.error('Error deleting patient:', error);
    } finally {
      setDeleteLoading(false);
    }
  };



  // No longer filtering client-side
  const filteredPatients = patients;

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };

  const getLocalizedGender = (gender?: string) => {
    if (!gender) return t('common.na');
    const normalized = gender.trim().toLowerCase();
    if (normalized === 'male' || normalized === 'm') return t('common.male');
    if (normalized === 'female' || normalized === 'f') return t('common.female');
    if (normalized === 'other' || normalized === 'o') return t('common.other');
    return gender;
  };

  return (
    <div className="space-y-8">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl md:text-4xl font-extrabold text-foreground tracking-tight">{t('patients.title')}</h2>
          <p className="text-muted-foreground mt-1 text-base md:text-lg">{t('patients.managePatients')}</p>
        </div>
        <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">

          <Button
            className="gap-2 font-bold px-6 py-6 text-md shadow-md hover:shadow-lg transition-all w-full sm:w-auto"
            variant="secondary"
            onClick={() => {
              setSelectedPatient(null);
              setIsDialogOpen(true);
            }}
          >
            <Plus className="h-5 w-5" />
            {t('patients.addPatient')}
          </Button>
        </div>
      </div>

      <div className="bg-card p-1 rounded-xl shadow-sm">
        <Input
          className="h-12 text-lg px-4 border-0 focus-visible:ring-0 bg-transparent"
          placeholder={t('patients.searchPlaceholder')}
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={handlePageChange}
        maxPageButtons={5}
        alignment="right"
        showSummary={false}
        showPageSize={false}
        loading={loading}
        className="border-0 px-0 py-0"
        labels={{
          showing: t('common.showing'),
          to: t('common.to'),
          of: t('common.of'),
          perPage: t('common.perPage'),
          previous: t('common.previous'),
          next: t('common.next'),
        }}
      />

      <div className="bg-white rounded-2xl border shadow-xl overflow-hidden">
        {loading ? (
          <div className="p-8 text-center text-muted-foreground">{t('common.loading')}</div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t('common.name')}</TableHead>
                <TableHead>{t('common.email')}</TableHead>
                <TableHead>{t('common.phone')}</TableHead>
                <TableHead>{t('common.gender')}</TableHead>
                <TableHead>{t('common.dateOfBirth')}</TableHead>
                <TableHead className='text-center'>{t('common.actions')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredPatients.length > 0 ? (
                filteredPatients.map((patient) => (
                  <TableRow key={patient._id}>
                    <TableCell className="font-medium">
                      {patient.userId.firstName} {patient.userId.lastName}
                    </TableCell>
                    <TableCell>{patient?.userId.email}</TableCell>
                    <TableCell>{patient.userId.phone || t('common.na')}</TableCell>
                    <TableCell>{getLocalizedGender(patient.gender)}</TableCell>
                    <TableCell>
                      {patient.dateOfBirth
                        ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' })
                        : t('common.na')}
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-2 items-center justify-center whitespace-nowrap">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => router.push(`/patients/${patient._id}`)}
                        >
                          <Eye className="h-4 w-4 mr-1" /> {t('common.view')}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSelectedPatient(patient);
                            setIsDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4 mr-1" /> {t('common.edit')}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDelete(patient)}
                        >
                          <Trash2 className="h-4 w-4 mr-1 text-red-500" /> {t('common.delete')}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSurveyPatientId(patient._id);
                            setIsSurveyDialogOpen(true);
                          }}
                        >
                          <Star className="h-4 w-4 mr-1 text-yellow-500" /> {t('common.feedback')}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-6 text-muted-foreground">
                    {t('common.noResults')}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={handlePageChange}
        maxPageButtons={5}
        loading={loading}
        pageSize={pageSize}
        pageSizeOptions={[5, 10, 25, 50]}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setCurrentPage(1);
        }}
        showingFrom={totalPatients > 0 ? (currentPage - 1) * pageSize + 1 : 0}
        showingTo={Math.min(currentPage * pageSize, totalPatients)}
        totalItems={totalPatients}
        labels={{
          showing: t('common.showing'),
          to: t('common.to'),
          of: t('common.of'),
          perPage: t('common.perPage'),
          previous: t('common.previous'),
          next: t('common.next'),
        }}
      />

      {/* Edit/Create Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="w-full max-h-[90vh] overflow-y-auto sm:px-8 sm:mx-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedPatient ? t('patients.editPatient') : t('patients.addPatient')}
            </DialogTitle>
          </DialogHeader>
          <PatientForm
            key={selectedPatient ? selectedPatient._id : 'new'}
            initialData={selectedPatient}
            onSuccess={() => {
              setIsDialogOpen(false);
              fetchPatients(currentPage, debouncedSearchTerm);
            }}
            onCancel={() => setIsDialogOpen(false)}
          />
        </DialogContent>
      </Dialog>


      {/* Survey Dialog */}
      <Dialog open={isSurveyDialogOpen} onOpenChange={setIsSurveyDialogOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>{t('survey.title')}</DialogTitle>
            <DialogDescription>
              {t('survey.description')}
            </DialogDescription>
          </DialogHeader>
          {surveyPatientId && (
            <SurveyForm
              patientId={surveyPatientId}
              onSuccess={() => {
                setIsSurveyDialogOpen(false);
                setSurveyPatientId(null);
              }}
              onCancel={() => {
                setIsSurveyDialogOpen(false);
                setSurveyPatientId(null);
              }}
            />
          )}
        </DialogContent>
      </Dialog>

      <ConfirmDialog
        open={!!pendingDeletePatient}
        onOpenChange={(open) => !open && setPendingDeletePatient(null)}
        title={t('common.confirmDelete')}
        confirmLabel={t('common.delete')}
        cancelLabel={t('common.cancel')}
        loading={deleteLoading}
        onConfirm={confirmDelete}
      />
    </div>
  );
}
