'use client';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { Edit, Plus, Trash2 } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import DoctorForm from './DoctorForm';
import ConfirmDialog from '@/components/common/ConfirmDialog';
import PaginationControls from '@/components/common/PaginationControls';
import { useDebounce } from '@/hooks/use-debounce';

interface Doctor {
  _id: string;
  userId: {
    _id: string;
    firstName: string;
    lastName: string;
    email: string;
    phone?: string;
    ownerId?: {
      _id?: string;
      firstName?: string;
      lastName?: string;
      email?: string;
    } | string | null;
  };
  isDentist: boolean;
  licenseNumber?: string;
  createdAt: string;
}

interface PaginationInfo {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

export default function DoctorList() {
  const { t } = useLanguage();
  const { user } = useAuthStore();
  const isAdmin = user?.userType === 'admin';
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 400);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedDoctor, setSelectedDoctor] = useState<Doctor | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [paginationInfo, setPaginationInfo] = useState<PaginationInfo | null>(null);
  const [pendingDeleteDoctor, setPendingDeleteDoctor] = useState<Doctor | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  const fetchDoctors = useCallback(async (page: number, search: string = '') => {
    try {
      setLoading(true);
      const query = new URLSearchParams({
        page: String(page),
        limit: String(pageSize),
      });
      if (search.trim()) {
        query.append('search', search.trim());
      }
      const response = await fetch(`${API_BASE_URL}/api/doctors?${query.toString()}`);
      const data = await response.json();
      if (data.success) {
        setDoctors(data.data);
        setPaginationInfo(data.pagination);
      }
    } catch (error) {
      console.error('Error fetching doctors:', error);
    } finally {
      setLoading(false);
    }
  }, [pageSize]);

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

  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearchTerm]);

  const handleDelete = (doctor: Doctor) => {
    setPendingDeleteDoctor(doctor);
  };

  const confirmDelete = async () => {
    if (!pendingDeleteDoctor) return;
    try {
      setDeleteLoading(true);
      const response = await fetch(`${API_BASE_URL}/api/doctors/${pendingDeleteDoctor._id}`, {
        method: 'DELETE',
      });
      if (response.ok) {
        setPendingDeleteDoctor(null);
        fetchDoctors(currentPage);
      }
    } catch (error) {
      console.error('Error deleting doctor:', error);
    } finally {
      setDeleteLoading(false);
    }
  };

  const filteredDoctors = doctors;

  const getAccountTypeLabel = (doctor: Doctor) =>
    doctor.userId?.ownerId ? t('common.teammate') : t('common.primaryDoctor');

  const getAccountTypeStyles = (doctor: Doctor) =>
    doctor.userId?.ownerId
      ? 'bg-slate-100 text-slate-700'
      : 'bg-cyan-100 text-cyan-800';

  const getPrimaryDoctorLabel = (doctor: Doctor) => {
    if (!doctor.userId?.ownerId || typeof doctor.userId.ownerId === 'string') return '';
    const owner = doctor.userId.ownerId;
    const fullName = `${owner.firstName || ''} ${owner.lastName || ''}`.trim();
    return fullName ? `${t('common.primaryDoctor')}: ${fullName}` : '';
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-3xl font-bold">{t('doctors.title')}</h2>
        <Button
          className="h-12 gap-2"
          onClick={() => {
            setSelectedDoctor(null);
            setIsDialogOpen(true);
          }}
        >
          <Plus className="h-4 w-4" />
          {t('doctors.addDoctor')}
        </Button>
      </div>

      <div className="space-y-4">
        {/* Search Input */}
        <Input
          placeholder={t('doctors.searchPlaceholder')}
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="h-12"
        />
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={paginationInfo?.totalPages || 1}
        onPageChange={setCurrentPage}
        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-lg border">
        <div className="px-6 py-4 border-b">
          <p className="text-sm text-gray-600">
            {filteredDoctors.length === 0 && doctors.length > 0
              ? t('doctors.noMatchFilters')
              : `${paginationInfo?.total ?? filteredDoctors.length} ${t('doctors.doctorsFound')}`}
          </p>
        </div>
        {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('doctors.type')}</TableHead>
                <TableHead>{t('common.phone')}</TableHead>
                <TableHead>{t('doctors.licenseNumber')}</TableHead>
                <TableHead>{t('common.actions')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredDoctors.length > 0 ? (
                filteredDoctors.map((doctor) => (
                  <TableRow key={doctor._id}>
                    <TableCell className="font-medium">
                      <div>
                        <div className="flex items-center gap-2">
                          <span>{doctor.userId?.firstName} {doctor.userId?.lastName}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full ${getAccountTypeStyles(doctor)}`}>
                            {getAccountTypeLabel(doctor)}
                          </span>
                        </div>
                        {doctor.userId?.ownerId && (
                          <div className="text-xs text-slate-500 mt-1">
                            {getPrimaryDoctorLabel(doctor)}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>{doctor.userId?.email}</TableCell>
                    <TableCell>{doctor.isDentist ? t('doctors.dentistType') : t('doctors.doctorType')}</TableCell>
                    <TableCell>{doctor.userId?.phone || t('common.na')}</TableCell>
                    <TableCell>{doctor.licenseNumber || t('common.na')}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setSelectedDoctor(doctor);
                            setIsDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(doctor)}
                        >
                          <Trash2 className="h-4 w-4 text-red-500" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8 text-gray-500">
                    {t('common.noData')}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={paginationInfo?.totalPages || 1}
        onPageChange={setCurrentPage}
        maxPageButtons={5}
        loading={loading}
        pageSize={pageSize}
        pageSizeOptions={[5, 10, 25, 50]}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setCurrentPage(1);
        }}
        showingFrom={filteredDoctors.length > 0 ? (currentPage - 1) * pageSize + 1 : 0}
        showingTo={Math.min(currentPage * pageSize, (paginationInfo?.total || filteredDoctors.length))}
        totalItems={paginationInfo?.total || filteredDoctors.length}
        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'),
        }}
      />

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>
              {selectedDoctor ? t('doctors.editDoctor') : t('doctors.addDoctor')}
            </DialogTitle>
          </DialogHeader>
          <DoctorForm
            initialData={selectedDoctor ? {
              _id: selectedDoctor._id,
              userId: selectedDoctor.userId._id,
              firstName: selectedDoctor.userId.firstName,
              lastName: selectedDoctor.userId.lastName,
              email: selectedDoctor.userId.email,
              isDentist: selectedDoctor.isDentist,
              phone: selectedDoctor.userId.phone,
              licenseNumber: selectedDoctor.licenseNumber
            } : null}
            isAdmin={isAdmin}
            onSuccess={() => {
              setIsDialogOpen(false);
              fetchDoctors(currentPage, debouncedSearchTerm);
            }}
            onCancel={() => setIsDialogOpen(false)}
          />
        </DialogContent>
      </Dialog>

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