import { useState } from 'react';
import { ViolationRecord } from '../../../types/driver';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Textarea } from '../../ui/textarea';
import { Badge } from '../../ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../../ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../../ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../../ui/alert-dialog';
import { Plus, Edit, Trash2, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface ViolationRecordManagementProps {
  driverId: string;
  records: ViolationRecord[];
  onUpdate: (records: ViolationRecord[]) => void;
}

export function ViolationRecordManagement({
  driverId,
  records,
  onUpdate,
}: ViolationRecordManagementProps) {
  const [showDialog, setShowDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingRecord, setEditingRecord] = useState<ViolationRecord | null>(null);
  const [deletingRecord, setDeletingRecord] = useState<ViolationRecord | null>(null);

  const [formData, setFormData] = useState({
    violationType: '',
    violationDate: '',
    description: '',
    penaltyPoints: '',
    fine: '',
    handler: '',
    status: '待处理' as '待处理' | '处理中' | '已处理',
    remarks: '',
  });

  const handleAdd = () => {
    setEditingRecord(null);
    setFormData({
      violationType: '',
      violationDate: '',
      description: '',
      penaltyPoints: '',
      fine: '',
      handler: '',
      status: '待处理',
      remarks: '',
    });
    setShowDialog(true);
  };

  const handleEdit = (record: ViolationRecord) => {
    setEditingRecord(record);
    setFormData({
      violationType: record.violationType,
      violationDate: record.violationDate,
      description: record.description,
      penaltyPoints: record.penaltyPoints?.toString() || '',
      fine: record.fine?.toString() || '',
      handler: record.handler || '',
      status: record.status,
      remarks: record.remarks || '',
    });
    setShowDialog(true);
  };

  const handleSave = () => {
    if (!formData.violationType.trim()) {
      toast.error('请输入违规类型');
      return;
    }
    if (!formData.violationDate) {
      toast.error('请选择违规日期');
      return;
    }
    if (!formData.description.trim()) {
      toast.error('请输入违规描述');
      return;
    }

    if (editingRecord) {
      // 编辑
      const updatedRecords = records.map(record =>
        record.id === editingRecord.id
          ? {
              ...record,
              violationType: formData.violationType,
              violationDate: formData.violationDate,
              description: formData.description,
              penaltyPoints: formData.penaltyPoints ? parseInt(formData.penaltyPoints) : undefined,
              fine: formData.fine ? parseFloat(formData.fine) : undefined,
              handler: formData.handler,
              status: formData.status,
              remarks: formData.remarks,
            }
          : record
      );
      onUpdate(updatedRecords);
      toast.success('违规记录更新成功');
    } else {
      // 新增
      const newRecord: ViolationRecord = {
        id: `violation-${Date.now()}`,
        driverId,
        violationType: formData.violationType,
        violationDate: formData.violationDate,
        description: formData.description,
        penaltyPoints: formData.penaltyPoints ? parseInt(formData.penaltyPoints) : undefined,
        fine: formData.fine ? parseFloat(formData.fine) : undefined,
        handler: formData.handler,
        status: formData.status,
        remarks: formData.remarks,
      };
      onUpdate([...records, newRecord]);
      toast.success('违规记录添加成功');
    }

    setShowDialog(false);
  };

  const handleDeleteClick = (record: ViolationRecord) => {
    setDeletingRecord(record);
    setShowDeleteDialog(true);
  };

  const handleDelete = () => {
    if (deletingRecord) {
      const updatedRecords = records.filter(record => record.id !== deletingRecord.id);
      onUpdate(updatedRecords);
      toast.success('违规记录删除成功');
      setShowDeleteDialog(false);
      setDeletingRecord(null);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '已处理':
        return 'bg-green-100 text-green-700';
      case '处理中':
        return 'bg-blue-100 text-blue-700';
      case '待处理':
        return 'bg-orange-100 text-orange-700';
      default:
        return 'bg-gray-100 text-gray-700';
    }
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <AlertTriangle className="w-5 h-5 text-red-600" />
          <h4 className="text-red-800">违规记录</h4>
        </div>
        <Button
          size="sm"
          className="bg-red-600 hover:bg-red-700"
          onClick={handleAdd}
        >
          <Plus className="w-4 h-4 mr-2" />
          新增记录
        </Button>
      </div>

      {records.length === 0 ? (
        <div className="text-center text-muted-foreground py-8">
          暂无违规记录
        </div>
      ) : (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>违规类型</TableHead>
              <TableHead>违规日期</TableHead>
              <TableHead>违规描述</TableHead>
              <TableHead>扣分</TableHead>
              <TableHead>罚款</TableHead>
              <TableHead>处理人</TableHead>
              <TableHead>状态</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map((record) => (
              <TableRow key={record.id}>
                <TableCell className="font-medium">{record.violationType}</TableCell>
                <TableCell>{formatDate(record.violationDate)}</TableCell>
                <TableCell className="max-w-xs truncate">{record.description}</TableCell>
                <TableCell>
                  {record.penaltyPoints ? (
                    <Badge variant="destructive">{record.penaltyPoints}分</Badge>
                  ) : (
                    '-'
                  )}
                </TableCell>
                <TableCell>
                  {record.fine ? (
                    <span className="text-red-600">¥{record.fine}</span>
                  ) : (
                    '-'
                  )}
                </TableCell>
                <TableCell>{record.handler || '-'}</TableCell>
                <TableCell>
                  <Badge variant="secondary" className={getStatusColor(record.status)}>
                    {record.status}
                  </Badge>
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(record)}
                    >
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDeleteClick(record)}
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}

      {/* 新增/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingRecord ? '编辑违规记录' : '新增违规记录'}</DialogTitle>
            <DialogDescription>
              {editingRecord ? '修改违规记录信息' : '添加新的违规记录'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="violationType">违规类型 *</Label>
                <Input
                  id="violationType"
                  placeholder="如：超速行驶"
                  value={formData.violationType}
                  onChange={(e) =>
                    setFormData({ ...formData, violationType: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="violationDate">违规日期 *</Label>
                <Input
                  id="violationDate"
                  type="date"
                  value={formData.violationDate}
                  onChange={(e) =>
                    setFormData({ ...formData, violationDate: e.target.value })
                  }
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">违规描述 *</Label>
              <Textarea
                id="description"
                placeholder="请详细描述违规情况..."
                rows={3}
                value={formData.description}
                onChange={(e) =>
                  setFormData({ ...formData, description: e.target.value })
                }
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="penaltyPoints">扣分</Label>
                <Input
                  id="penaltyPoints"
                  type="number"
                  min="0"
                  placeholder="2"
                  value={formData.penaltyPoints}
                  onChange={(e) =>
                    setFormData({ ...formData, penaltyPoints: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="fine">罚款(元)</Label>
                <Input
                  id="fine"
                  type="number"
                  min="0"
                  step="0.01"
                  placeholder="200"
                  value={formData.fine}
                  onChange={(e) =>
                    setFormData({ ...formData, fine: e.target.value })
                  }
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="handler">处理人</Label>
                <Input
                  id="handler"
                  placeholder="如：安全员王五"
                  value={formData.handler}
                  onChange={(e) =>
                    setFormData({ ...formData, handler: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">处理状态</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value: '待处理' | '处理中' | '已处理') =>
                    setFormData({ ...formData, status: value })
                  }
                >
                  <SelectTrigger id="status">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="待处理">待处理</SelectItem>
                    <SelectItem value="处理中">处理中</SelectItem>
                    <SelectItem value="已处理">已处理</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="remarks">备注</Label>
              <Textarea
                id="remarks"
                placeholder="请输入备注信息..."
                rows={3}
                value={formData.remarks}
                onChange={(e) =>
                  setFormData({ ...formData, remarks: e.target.value })
                }
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-red-600 hover:bg-red-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除违规记录 <span className="font-semibold">"{deletingRecord?.violationType}"</span> 吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={handleDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </Card>
  );
}
