import { useState, useEffect } from 'react';
import { Button } from '../ui/button';
import { Card } from '../ui/card';
import { Plus, Bell, Calendar, AlertCircle } from 'lucide-react';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { DriverList } from './driver/DriverList';
import { DriverForm } from './driver/DriverForm';
import { DriverDetails } from './driver/DriverDetails';
import { DriverTaskManagement } from './driver/DriverTaskManagement';
import { CertificateReminders } from './driver/CertificateReminders';
import { DriverRecord } from '../../types/driver';

export function DriverArchive() {
  const [drivers, setDrivers] = useState<DriverRecord[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [editingDriver, setEditingDriver] = useState<DriverRecord | undefined>();
  const [selectedDriver, setSelectedDriver] = useState<DriverRecord | null>(null);
  const [activeTab, setActiveTab] = useState('list');

  useEffect(() => {
    loadDrivers();
  }, []);

  const loadDrivers = () => {
    const data = localStorage.getItem('smart_agriculture_drivers');
    if (data) {
      setDrivers(JSON.parse(data));
    } else {
      // 初始化示例数据
      const mockDrivers: DriverRecord[] = [
        {
          id: 'driver-1',
          name: '张三',
          gender: '男',
          birthDate: '1985-03-15',
          phone: '13800138001',
          email: 'zhangsan@example.com',
          address: '山东省济南市历城区农机路123号',
          idCard: '370102198503151234',
          driverLicense: {
            licenseNumber: 'C1234567890',
            licenseType: 'C1',
            issueDate: '2020-01-01',
            expiryDate: '2026-01-01',
          },
          qualification: {
            certificateNumber: 'Q1234567890',
            issueDate: '2020-03-01',
            expiryDate: '2025-03-01',
          },
          trainingRecords: [],
          violationRecords: [],
          status: '在岗',
          department: '第一生产队',
          entryDate: '2020-01-15',
          createdAt: '2020-01-15T08:00:00.000Z',
          updatedAt: '2020-01-15T08:00:00.000Z',
          createdBy: '系统管理员',
          updatedBy: '系统管理员',
        },
        {
          id: 'driver-2',
          name: '李四',
          gender: '男',
          birthDate: '1990-06-20',
          phone: '13800138002',
          address: '山东省济南市历城区农机路124号',
          idCard: '370102199006201234',
          driverLicense: {
            licenseNumber: 'B1234567891',
            licenseType: 'B2',
            issueDate: '2019-06-01',
            expiryDate: '2025-06-01',
          },
          trainingRecords: [],
          violationRecords: [],
          status: '在岗',
          department: '第二生产队',
          entryDate: '2019-07-01',
          createdAt: '2019-07-01T08:00:00.000Z',
          updatedAt: '2019-07-01T08:00:00.000Z',
          createdBy: '系统管理员',
          updatedBy: '系统管理员',
        },
      ];
      localStorage.setItem('smart_agriculture_drivers', JSON.stringify(mockDrivers));
      setDrivers(mockDrivers);
    }
  };

  const handleSaveDriver = (data: Partial<DriverRecord>) => {
    const now = new Date().toISOString();
    
    if (editingDriver) {
      const updated = {
        ...editingDriver,
        ...data,
        updatedAt: now,
        updatedBy: '系统管理员',
      };
      const newDrivers = drivers.map(d => d.id === updated.id ? updated : d);
      setDrivers(newDrivers);
      localStorage.setItem('smart_agriculture_drivers', JSON.stringify(newDrivers));
    } else {
      const newDriver: DriverRecord = {
        id: `driver-${Date.now()}`,
        ...data as DriverRecord,
        trainingRecords: [],
        violationRecords: [],
        createdAt: now,
        updatedAt: now,
        createdBy: '系统管理员',
        updatedBy: '系统管理员',
      };
      const newDrivers = [...drivers, newDriver];
      setDrivers(newDrivers);
      localStorage.setItem('smart_agriculture_drivers', JSON.stringify(newDrivers));
    }
    
    setShowForm(false);
    setEditingDriver(undefined);
  };

  const handleDeleteDriver = (id: string) => {
    const newDrivers = drivers.filter(d => d.id !== id);
    setDrivers(newDrivers);
    localStorage.setItem('smart_agriculture_drivers', JSON.stringify(newDrivers));
  };

  const handleViewDetails = (driver: DriverRecord) => {
    setSelectedDriver(driver);
    setShowDetails(true);
  };

  const handleEdit = (driver: DriverRecord) => {
    setEditingDriver(driver);
    setShowForm(true);
  };

  // 计算证件到期提醒
  const getExpiringCertificates = () => {
    const today = new Date();
    const thirtyDaysLater = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000);
    
    const reminders = drivers.flatMap(driver => {
      const results = [];
      
      // 检查驾驶证
      const licenseExpiry = new Date(driver.driverLicense.expiryDate);
      if (licenseExpiry <= thirtyDaysLater) {
        const daysUntil = Math.ceil((licenseExpiry.getTime() - today.getTime()) / (24 * 60 * 60 * 1000));
        results.push({
          driverId: driver.id,
          driverName: driver.name,
          certificateType: '驾驶证' as const,
          expiryDate: driver.driverLicense.expiryDate,
          daysUntilExpiry: daysUntil,
          reminded: false,
        });
      }
      
      // 检查从业资格证
      if (driver.qualification) {
        const qualExpiry = new Date(driver.qualification.expiryDate);
        if (qualExpiry <= thirtyDaysLater) {
          const daysUntil = Math.ceil((qualExpiry.getTime() - today.getTime()) / (24 * 60 * 60 * 1000));
          results.push({
            driverId: driver.id,
            driverName: driver.name,
            certificateType: '从业资格证' as const,
            expiryDate: driver.qualification.expiryDate,
            daysUntilExpiry: daysUntil,
            reminded: false,
          });
        }
      }
      
      return results;
    });
    
    return reminders;
  };

  const expiringCerts = getExpiringCertificates();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">驾驶员档案</h2>
          <p className="text-muted-foreground">驾驶员信息与任务管理</p>
        </div>
        <div className="flex gap-2">
          <Button onClick={() => setShowForm(true)}>
            <Plus className="w-4 h-4 mr-2" />
            新增驾驶员
          </Button>
        </div>
      </div>

      {/* 证件到期提醒 */}
      {expiringCerts.length > 0 && (
        <Card className="p-4 bg-warning-muted border-warning">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-warning mt-0.5" />
            <div className="flex-1">
              <h4 className="text-foreground">证件到期提醒</h4>
              <div className="mt-2 space-y-1">
                {expiringCerts.map((cert, index) => (
                  <p key={index} className="text-sm text-warning">
                    {cert.driverName} 的{cert.certificateType}将于 {cert.daysUntilExpiry} 天后到期
                    （{new Date(cert.expiryDate).toLocaleDateString('zh-CN')}）
                  </p>
                ))}
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总驾驶员</div>
          <div className="mt-1">{drivers.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">在岗</div>
          <div className="mt-1 text-success">
            {drivers.filter(d => d.status === '在岗').length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">休假</div>
          <div className="mt-1 text-info">
            {drivers.filter(d => d.status === '休假').length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">证件即将到期</div>
          <div className="mt-1 text-warning">{expiringCerts.length}</div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          <TabsTrigger value="list">驾驶员列表</TabsTrigger>
          <TabsTrigger value="tasks">任务管理</TabsTrigger>
          <TabsTrigger value="reminders">证件提醒</TabsTrigger>
        </TabsList>

        <TabsContent value="list" className="mt-6">
          <DriverList
            drivers={drivers}
            onEdit={handleEdit}
            onDelete={handleDeleteDriver}
            onViewDetails={handleViewDetails}
          />
        </TabsContent>

        <TabsContent value="tasks" className="mt-6">
          <DriverTaskManagement drivers={drivers} />
        </TabsContent>

        <TabsContent value="reminders" className="mt-6">
          <CertificateReminders reminders={expiringCerts} drivers={drivers} />
        </TabsContent>
      </Tabs>

      <DriverForm
        open={showForm}
        onClose={() => {
          setShowForm(false);
          setEditingDriver(undefined);
        }}
        onSave={handleSaveDriver}
        initialData={editingDriver}
      />

      <DriverDetails
        open={showDetails}
        onClose={() => {
          setShowDetails(false);
          setSelectedDriver(null);
        }}
        driver={selectedDriver}
        onReload={loadDrivers}
      />
    </div>
  );
}
