import { useState } from 'react';
import { TrainingRecord } 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 {
  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, Award } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

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

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

  const [formData, setFormData] = useState({
    trainingName: '',
    trainingType: '',
    trainingDate: '',
    duration: '',
    instructor: '',
    score: '',
    remarks: '',
  });

  const handleAdd = () => {
    setEditingRecord(null);
    setFormData({
      trainingName: '',
      trainingType: '',
      trainingDate: '',
      duration: '',
      instructor: '',
      score: '',
      remarks: '',
    });
    setShowDialog(true);
  };

  const handleEdit = (record: TrainingRecord) => {
    setEditingRecord(record);
    setFormData({
      trainingName: record.trainingName,
      trainingType: record.trainingType,
      trainingDate: record.trainingDate,
      duration: record.duration.toString(),
      instructor: record.instructor || '',
      score: record.score?.toString() || '',
      remarks: record.remarks || '',
    });
    setShowDialog(true);
  };

  const handleSave = () => {
    if (!formData.trainingName.trim()) {
      toast.error('请输入培训名称');
      return;
    }
    if (!formData.trainingType.trim()) {
      toast.error('请输入培训类型');
      return;
    }
    if (!formData.trainingDate) {
      toast.error('请选择培训日期');
      return;
    }
    if (!formData.duration || parseFloat(formData.duration) <= 0) {
      toast.error('请输入有效的培训时长');
      return;
    }

    if (editingRecord) {
      // 编辑
      const updatedRecords = records.map(record =>
        record.id === editingRecord.id
          ? {
              ...record,
              trainingName: formData.trainingName,
              trainingType: formData.trainingType,
              trainingDate: formData.trainingDate,
              duration: parseFloat(formData.duration),
              instructor: formData.instructor,
              score: formData.score ? parseFloat(formData.score) : undefined,
              remarks: formData.remarks,
            }
          : record
      );
      onUpdate(updatedRecords);
      toast.success('培训记录更新成功');
    } else {
      // 新增
      const newRecord: TrainingRecord = {
        id: `training-${Date.now()}`,
        driverId,
        trainingName: formData.trainingName,
        trainingType: formData.trainingType,
        trainingDate: formData.trainingDate,
        duration: parseFloat(formData.duration),
        instructor: formData.instructor,
        score: formData.score ? parseFloat(formData.score) : undefined,
        remarks: formData.remarks,
      };
      onUpdate([...records, newRecord]);
      toast.success('培训记录添加成功');
    }

    setShowDialog(false);
  };

  const handleDeleteClick = (record: TrainingRecord) => {
    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 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">
          <Award className="w-5 h-5 text-green-600" />
          <h4 className="text-green-800">培训记录</h4>
        </div>
        <Button
          size="sm"
          className="bg-green-600 hover:bg-green-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 className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map((record) => (
              <TableRow key={record.id}>
                <TableCell className="font-medium">{record.trainingName}</TableCell>
                <TableCell>
                  <Badge variant="outline">{record.trainingType}</Badge>
                </TableCell>
                <TableCell>{formatDate(record.trainingDate)}</TableCell>
                <TableCell>{record.duration}</TableCell>
                <TableCell>{record.instructor || '-'}</TableCell>
                <TableCell>
                  {record.score ? (
                    <Badge
                      variant="secondary"
                      className={
                        record.score >= 90
                          ? 'bg-green-100 text-green-700'
                          : record.score >= 60
                          ? 'bg-blue-100 text-blue-700'
                          : 'bg-red-100 text-red-700'
                      }
                    >
                      {record.score}分
                    </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="trainingName">培训名称 *</Label>
                <Input
                  id="trainingName"
                  placeholder="如：农机安全操作培训"
                  value={formData.trainingName}
                  onChange={(e) =>
                    setFormData({ ...formData, trainingName: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="trainingType">培训类型 *</Label>
                <Input
                  id="trainingType"
                  placeholder="如：安全培训"
                  value={formData.trainingType}
                  onChange={(e) =>
                    setFormData({ ...formData, trainingType: e.target.value })
                  }
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="trainingDate">培训日期 *</Label>
                <Input
                  id="trainingDate"
                  type="date"
                  value={formData.trainingDate}
                  onChange={(e) =>
                    setFormData({ ...formData, trainingDate: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="duration">培训时长(小时) *</Label>
                <Input
                  id="duration"
                  type="number"
                  min="0"
                  step="0.5"
                  placeholder="8"
                  value={formData.duration}
                  onChange={(e) =>
                    setFormData({ ...formData, duration: e.target.value })
                  }
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="instructor">培训师</Label>
                <Input
                  id="instructor"
                  placeholder="如：李教员"
                  value={formData.instructor}
                  onChange={(e) =>
                    setFormData({ ...formData, instructor: e.target.value })
                  }
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="score">成绩</Label>
                <Input
                  id="score"
                  type="number"
                  min="0"
                  max="100"
                  placeholder="95"
                  value={formData.score}
                  onChange={(e) =>
                    setFormData({ ...formData, score: e.target.value })
                  }
                />
              </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-green-600 hover:bg-green-700" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

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