import { useState } from 'react';
import { DriverRecord } from '../../../types/driver';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Button } from '../../ui/button';
import { Badge } from '../../ui/badge';
import { Card } from '../../ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../../ui/alert-dialog';
import { Edit, Trash2, Eye } from 'lucide-react';
import { usePagination } from '../../../lib/usePagination';
import { DataPagination } from '../../ui/data-pagination';

interface DriverListProps {
  drivers: DriverRecord[];
  onEdit: (driver: DriverRecord) => void;
  onDelete: (id: string) => void;
  onViewDetails: (driver: DriverRecord) => void;
}

export function DriverList({ drivers, onEdit, onDelete, onViewDetails }: DriverListProps) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string>('');

  const handleDeleteClick = (id: string) => {
    setDeletingId(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    onDelete(deletingId);
    setDeleteDialogOpen(false);
    setDeletingId('');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '在岗': return 'bg-success-muted text-success';
      case '休假': return 'bg-info-muted text-info';
      case '离职': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const checkCertificateExpiry = (expiryDate: string) => {
    const today = new Date();
    const expiry = new Date(expiryDate);
    const daysUntil = Math.ceil((expiry.getTime() - today.getTime()) / (24 * 60 * 60 * 1000));
    
    if (daysUntil < 0) return { status: 'expired', color: 'text-error', text: '已过期' };
    if (daysUntil <= 30) return { status: 'expiring', color: 'text-warning', text: `${daysUntil}天后到期` };
    return { status: 'valid', color: 'text-success', text: '有效' };
  };

  // 分页
  const pagination = usePagination(drivers, 10);

  return (
    <Card>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>姓名</TableHead>
            <TableHead>性别</TableHead>
            <TableHead>联系电话</TableHead>
            <TableHead>驾驶证类型</TableHead>
            <TableHead>驾驶证状态</TableHead>
            <TableHead>从业资格证</TableHead>
            <TableHead>部门</TableHead>
            <TableHead>状态</TableHead>
            <TableHead>操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {pagination.paginatedData.length === 0 ? (
            <TableRow>
              <TableCell colSpan={9} className="text-center text-muted-foreground py-8">
                暂无数据
              </TableCell>
            </TableRow>
          ) : (
            pagination.paginatedData.map((driver) => {
              const licenseStatus = checkCertificateExpiry(driver.driverLicense.expiryDate);
              const qualStatus = driver.qualification 
                ? checkCertificateExpiry(driver.qualification.expiryDate)
                : null;
              
              return (
                <TableRow key={driver.id}>
                  <TableCell>{driver.name}</TableCell>
                  <TableCell>{driver.gender}</TableCell>
                  <TableCell>{driver.phone}</TableCell>
                  <TableCell>{driver.driverLicense.licenseType}</TableCell>
                  <TableCell className={licenseStatus.color}>
                    {licenseStatus.text}
                  </TableCell>
                  <TableCell className={qualStatus?.color || 'text-gray-600'}>
                    {qualStatus?.text || '未登记'}
                  </TableCell>
                  <TableCell>{driver.department || '-'}</TableCell>
                  <TableCell>
                    <Badge variant="secondary" className={getStatusColor(driver.status)}>
                      {driver.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button variant="ghost" size="sm" onClick={() => onViewDetails(driver)}>
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => onEdit(driver)}>
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={() => handleDeleteClick(driver.id)}
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              );
            })
          )}
        </TableBody>
      </Table>

      {/* 分页 */}
      <DataPagination
        currentPage={pagination.currentPage}
        totalPages={pagination.totalPages}
        pageSize={pagination.pageSize}
        totalItems={drivers.length}
        startIndex={pagination.startIndex}
        endIndex={pagination.endIndex}
        onPageChange={pagination.goToPage}
        onPageSizeChange={pagination.setPageSize}
        canPreviousPage={pagination.canPreviousPage}
        canNextPage={pagination.canNextPage}
      />

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这条驾驶员记录吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-error hover:bg-error/90"
              onClick={confirmDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Card>
  );
}
