import { MachineryRecord, MachineryChangeHistory } from '../../types/machinery';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Card } from '../ui/card';
import { Badge } from '../ui/badge';
import { ChangeHistory } from './ChangeHistory';
import { MaintenanceRecords } from './MaintenanceRecords';
import { Calendar, Package, FileText, Wrench, TrendingUp } from 'lucide-react';

interface MachineryDetailsProps {
  open: boolean;
  onClose: () => void;
  machinery: MachineryRecord | null;
  history: MachineryChangeHistory[];
  tags: { id: string; name: string; color: string }[];
}

export function MachineryDetails({ open, onClose, machinery, history, tags }: MachineryDetailsProps) {
  if (!machinery) return null;

  const machineryTags = tags.filter(tag => machinery.tags.includes(tag.id));

  const InfoRow = ({ label, value }: { label: string; value: any }) => (
    <div className="flex justify-between py-2 border-b">
      <span className="text-muted-foreground">{label}</span>
      <span>{value || '-'}</span>
    </div>
  );

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

  const formatCurrency = (amount?: number) => {
    if (!amount) return '-';
    return `¥${amount.toLocaleString()}`;
  };

  const formatMaintenanceCycle = () => {
    if (!machinery.maintenanceCycle) return '-';
    const unitMap = {
      day: '天',
      month: '月',
      year: '年'
    };
    const unit = machinery.maintenanceCycleUnit || 'month';
    return `${machinery.maintenanceCycle} ${unitMap[unit]}`;
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>农机全生命周期档案</DialogTitle>
          <DialogDescription className="sr-only">
            查看农机设备的完整档案信息
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 基本信息卡片 */}
          <Card className="p-6">
            <div className="flex items-start justify-between mb-4">
              <div>
                <h2 className="text-primary">{machinery.name}</h2>
                <p className="text-muted-foreground">{machinery.model}</p>
              </div>
              <Badge variant="secondary" className={
                machinery.status === '正常' ? 'bg-success-muted text-success' :
                machinery.status === '待维护' ? 'bg-warning-muted text-warning' :
                'bg-error-muted text-error'
              }>
                {machinery.status}
              </Badge>
            </div>
            
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline">{machinery.category}</Badge>
              <Badge variant="outline">{machinery.usage}</Badge>
              {machineryTags.map(tag => (
                <Badge key={tag.id} style={{ backgroundColor: tag.color, color: 'white' }}>
                  {tag.name}
                </Badge>
              ))}
            </div>
          </Card>

          <Tabs defaultValue="basic" className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="basic">
                <FileText className="w-4 h-4 mr-2" />
                档案信息
              </TabsTrigger>
              <TabsTrigger value="technical">
                <Package className="w-4 h-4 mr-2" />
                技术参数
              </TabsTrigger>
              <TabsTrigger value="purchase">
                <TrendingUp className="w-4 h-4 mr-2" />
                购机信息
              </TabsTrigger>
              <TabsTrigger value="maintenance">
                <Wrench className="w-4 h-4 mr-2" />
                维护记录
              </TabsTrigger>
              <TabsTrigger value="history">
                <Calendar className="w-4 h-4 mr-2" />
                变更历史
              </TabsTrigger>
            </TabsList>

            {/* 档案信息 */}
            <TabsContent value="basic">
              <Card className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8">
                  <div>
                    <h4 className="mb-4">基本信息</h4>
                    <InfoRow label="设备名称" value={machinery.name} />
                    <InfoRow label="型号规格" value={machinery.model} />
                    <InfoRow label="农机类型" value={machinery.category} />
                    <InfoRow label="使用场景" value={machinery.usage} />
                    <InfoRow label="生产厂家" value={machinery.manufacturer} />
                    <InfoRow label="出厂日期" value={formatDate(machinery.manufactureDate)} />
                    <InfoRow label="购买日期" value={formatDate(machinery.purchaseDate)} />
                  </div>
                  <div>
                    <InfoRow label="设备状态" value={machinery.status} />
                    <InfoRow label="当前位置" value={machinery.currentLocation} />
                    <InfoRow label="保养周期" value={formatMaintenanceCycle()} />
                    <InfoRow label="创建时间" value={formatDate(machinery.createdAt)} />
                    <InfoRow label="创建人" value={machinery.createdBy} />
                    <InfoRow label="最后更新" value={formatDate(machinery.updatedAt)} />
                  </div>
                </div>
                {machinery.remarks && (
                  <div className="mt-4">
                    <h4 className="mb-2">备注</h4>
                    <p className="text-muted-foreground">{machinery.remarks}</p>
                  </div>
                )}
              </Card>
            </TabsContent>

            {/* 技术参数 */}
            <TabsContent value="technical">
              <Card className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8">
                  <InfoRow label="发动机号" value={machinery.engineNumber} />
                  <InfoRow label="车架号" value={machinery.chassisNumber} />
                  <InfoRow label="额定功率" value={machinery.power ? `${machinery.power} kW` : '-'} />
                  <InfoRow label="整机重量" value={machinery.weight ? `${machinery.weight} kg` : '-'} />
                  <InfoRow label="工作幅宽" value={machinery.workingWidth ? `${machinery.workingWidth} m` : '-'} />
                  <InfoRow label="油箱大小" value={machinery.fuelTankCapacity ? `${machinery.fuelTankCapacity} L` : '-'} />
                </div>
              </Card>
            </TabsContent>

            {/* 购机信息 */}
            <TabsContent value="purchase">
              <Card className="p-6">
                <div className="space-y-6">
                  <div>
                    <h4 className="mb-4">购机信息</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8">
                      <InfoRow label="购机价格" value={formatCurrency(machinery.purchasePrice)} />
                      <InfoRow label="供应商" value={machinery.supplier} />
                      <InfoRow label="发票号码" value={machinery.invoiceNumber} />
                      <InfoRow label="购机发票" value={machinery.invoiceUrl ? '已上传' : '未上传'} />
                    </div>
                  </div>

                  <div>
                    <h4 className="mb-4">保险信息</h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8">
                      <InfoRow label="保险公司" value={machinery.insuranceCompany} />
                      <InfoRow label="保单号" value={machinery.insurancePolicyNumber} />
                      <InfoRow label="保险起始日期" value={formatDate(machinery.insuranceStartDate)} />
                      <InfoRow label="保险结束日期" value={formatDate(machinery.insuranceEndDate)} />
                      <InfoRow label="保险金额" value={formatCurrency(machinery.insuranceAmount)} />
                    </div>
                  </div>
                </div>
              </Card>
            </TabsContent>

            {/* 维护记录 */}
            <TabsContent value="maintenance">
              <MaintenanceRecords machineryId={machinery.id} machineryName={machinery.name} />
            </TabsContent>

            {/* 变更历史 */}
            <TabsContent value="history">
              <ChangeHistory history={history} />
            </TabsContent>
          </Tabs>
        </div>
      </DialogContent>
    </Dialog>
  );
}
