import React, { useState, useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@d8d/shared-ui-components/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@d8d/shared-ui-components/components/ui/table';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Separator } from '@d8d/shared-ui-components/components/ui/separator';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@d8d/shared-ui-components/components/ui/radio-group';
import { Calendar } from '@d8d/shared-ui-components/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@d8d/shared-ui-components/components/ui/popover';
import { format } from 'date-fns';
import { CalendarIcon, Eye, Upload, X } from 'lucide-react';
import { toast } from 'sonner';
import { FileSelector } from '@d8d/file-management-ui/components';
import { AssetType, AssetFileType } from '@d8d/allin-order-module/schemas';
import { orderClientManager } from '../api/orderClient';

// 资产类型映射
const ASSET_TYPE_LABELS: Record<AssetType, string> = {
  [AssetType.DISABILITY_CERT]: '残疾证明',
  [AssetType.TAX]: '税务文件',
  [AssetType.SALARY]: '薪资单',
  [AssetType.JOB_RESULT]: '工作成果',
  [AssetType.CONTRACT_SIGN]: '合同签署',
  [AssetType.OTHER]: '其他',
};

interface OrderAssetModalProps {
  orderId: number;
  orderPersons: Array<{
    personId: number;
    personName: string;
    disabilityId?: string;
    disabilityType?: string;
  }>;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

interface AssetItem {
  id: number;
  assetType: AssetType;
  assetFileType: AssetFileType;
  fileId: number;
  file?: {
    id: number;
    name: string;
    type: string | null;
    size: number | null;
    path: string;
    fullUrl?: string;
    description: string | null;
    uploadTime: string;
  };
  relatedTime: string;
  remark?: string;
}

interface PersonAssetData {
  personId: number;
  personName: string;
  [key: string]: AssetItem | any; // 动态属性存储各种资产类型的数据
}

interface CurrentAsset {
  personId: number;
  personName: string;
  assetType: AssetType;
  assetItem?: AssetItem;
}

export const OrderAssetModal: React.FC<OrderAssetModalProps> = ({
  orderId,
  orderPersons,
  open,
  onOpenChange,
}) => {
  const queryClient = useQueryClient();
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [assetData, setAssetData] = useState<PersonAssetData[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploadModalOpen, setUploadModalOpen] = useState(false);
  const [previewModalOpen, setPreviewModalOpen] = useState(false);
  const [currentAsset, setCurrentAsset] = useState<CurrentAsset | null>(null);
  const [selectedFileId, setSelectedFileId] = useState<number | null>(null);
  const [uploadFileType, setUploadFileType] = useState<AssetFileType>(AssetFileType.IMAGE);
  const [uploading, setUploading] = useState(false);

  // 获取资产数据
  const fetchAssetData = async () => {
    if (!orderId || !orderPersons.length) return;

    setLoading(true);
    try {
      const personIds = orderPersons.map(person => person.personId);

      // 查询每个人员的资产
      const assetsPromises = personIds.map(personId =>
        orderClientManager.get().assets.query.$get({
          query: {
            orderId,
            personId,
            page: 1,
            limit: 100,
          },
        })
      );

      const responses = await Promise.all(assetsPromises);
      const assets = [];
      for (const response of responses) {
        if (response.ok) {
          const data = await response.json();
          assets.push(...data.data);
        }
      }


      // 按人员分组资产数据
      const groupedData: Record<number, PersonAssetData> = {};

      // 初始化人员数据
      orderPersons.forEach(person => {
        groupedData[person.personId] = {
          personId: person.personId,
          personName: person.personName,
        };
      });

      // 添加资产数据
      assets.forEach((asset: any) => {
        const { personId, assetType, id, assetFileType, fileId, file } = asset;
        if (groupedData[personId]) {
          groupedData[personId][assetType] = {
            id,
            assetType,
            assetFileType,
            fileId,
            file,
            relatedTime: asset.relatedTime,
            remark: asset.remark,
          };
        }
      });

      setAssetData(Object.values(groupedData));
    } catch (error) {
      toast.error('获取资产数据失败');
      console.error('获取资产数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 打开上传弹窗
  const handleOpenUploadModal = (personId: number, personName: string, assetType: AssetType) => {
    setCurrentAsset({
      personId,
      personName,
      assetType,
    });
    setSelectedFileId(null);
    setUploadFileType(AssetFileType.IMAGE);
    setUploadModalOpen(true);
  };

  // 打开预览弹窗
  const handleOpenPreviewModal = (personId: number, personName: string, assetType: AssetType, assetItem: AssetItem) => {
    setCurrentAsset({
      personId,
      personName,
      assetType,
      assetItem,
    });
    setPreviewModalOpen(true);
  };

  // 处理上传
  const handleUpload = async () => {
    if (!currentAsset || !orderId || !selectedFileId) {
      toast.error('请选择文件');
      return;
    }

    setUploading(true);
    try {
      const assetData = {
        orderId,
        personId: currentAsset.personId,
        assetType: currentAsset.assetType,
        assetFileType: uploadFileType,
        fileId: selectedFileId,
        relatedTime: format(selectedDate, 'yyyy-MM-dd'),
      };

      // 如果有现有资产，先删除再创建（模拟更新）
      if (currentAsset.assetItem && currentAsset.assetItem.id) {
        // 先删除旧资产
        const deleteResponse = await orderClientManager.get().assets.delete[':id'].$delete({
          param: { id: currentAsset.assetItem.id },
        });

        if (!deleteResponse.ok) {
          const error = await deleteResponse.json();
          throw new Error(error.message || '删除旧资产失败');
        }
      }

      // 创建新资产
      const response = await orderClientManager.get().assets.create.$post({
        json: assetData,
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '操作失败');
      }

      toast.success(currentAsset.assetItem ? '更新资产成功' : '上传资产成功');
      setUploadModalOpen(false);
      setPreviewModalOpen(false);
      fetchAssetData();
      queryClient.invalidateQueries({ queryKey: ['order-assets'] });
    } catch (error: any) {
      toast.error(`操作失败: ${error.message}`);
      console.error('操作失败:', error);
    } finally {
      setUploading(false);
    }
  };

  // 处理删除
  const handleDelete = async () => {
    if (!currentAsset?.assetItem?.id) return;

    try {
      const response = await orderClientManager.get().assets.delete[':id'].$delete({
        param: { id: currentAsset.assetItem.id },
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '删除资产失败');
      }

      toast.success('删除资产成功');
      setPreviewModalOpen(false);
      fetchAssetData();
      queryClient.invalidateQueries({ queryKey: ['order-assets'] });
    } catch (error: any) {
      toast.error(`删除资产失败: ${error.message}`);
      console.error('删除资产失败:', error);
    }
  };

  // 处理文件选择
  const handleFileChange = (fileId: number | null | number[]) => {
    if (fileId !== null && !Array.isArray(fileId)) {
      setSelectedFileId(fileId);
    } else {
      setSelectedFileId(null);
    }
  };

  // 获取资产类型列
  const assetTypeColumns = Object.values(AssetType).map(assetType => ({
    key: assetType,
    title: ASSET_TYPE_LABELS[assetType],
    dataIndex: assetType,
  }));

  // 表格列配置
  const columns = [
    {
      title: '残疾人ID',
      dataIndex: 'personId',
      key: 'personId',
      width: 100,
    },
    {
      title: '姓名',
      dataIndex: 'personName',
      key: 'personName',
      width: 120,
    },
    ...assetTypeColumns.map(col => ({
      title: col.title,
      dataIndex: col.key,
      key: col.key,
      width: 120,
    })),
  ];

  // 当日期或订单人员变化时重新获取数据
  useEffect(() => {
    if (open && orderId && orderPersons.length > 0) {
      fetchAssetData();
    }
  }, [open, selectedDate, orderId, orderPersons]);

  // 关闭弹窗时重置状态
  useEffect(() => {
    if (!open) {
      setSelectedDate(new Date());
      setAssetData([]);
      setCurrentAsset(null);
      setUploadModalOpen(false);
      setPreviewModalOpen(false);
    }
  }, [open]);

  return (
    <>
      {/* 主弹窗 */}
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[1200px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle data-testid="order-asset-modal-title">订单资源上传</DialogTitle>
            <DialogDescription>
              为订单中的残疾人管理资产文件（残疾证明、税务文件、薪资单等）
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 月份筛选 */}
            <div className="flex items-center space-x-2">
              <Label htmlFor="month-select">选择月份：</Label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={`w-[240px] justify-start text-left font-normal ${!selectedDate ? "text-muted-foreground" : ""}`}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {selectedDate ? format(selectedDate, "yyyy年MM月") : "选择月份"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    mode="single"
                    selected={selectedDate}
                    onSelect={(date) => date && setSelectedDate(date)}
                    initialFocus
                    className="p-3"
                      fromYear={2020}
                    toYear={2030}
                  />
                </PopoverContent>
              </Popover>
            </div>

            <Separator />

            {/* 资产表格 */}
            {loading ? (
              <div className="text-center py-8">加载资产数据...</div>
            ) : assetData.length > 0 ? (
              <div className="border rounded-md overflow-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      {columns.map(col => (
                        <TableHead key={col.key} style={{ width: col.width, minWidth: col.width }}>
                          {col.title}
                        </TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {assetData.map((record) => (
                      <TableRow key={record.personId}>
                        {columns.map(col => {
                          const value = record[col.dataIndex as keyof PersonAssetData];
                          if (col.key === 'personId' || col.key === 'personName') {
                            return (
                              <TableCell key={col.key}>
                                {value as React.ReactNode}
                              </TableCell>
                            );
                          } else {
                            // 资产类型列
                            const assetItem = value as AssetItem | undefined;
                            if (assetItem && assetItem.id) {
                              // 已上传，显示查看按钮
                              return (
                                <TableCell key={col.key}>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => handleOpenPreviewModal(record.personId, record.personName, col.key as AssetType, assetItem)}
                                  >
                                    <Eye className="h-4 w-4 mr-1" />
                                    查看文件
                                  </Button>
                                </TableCell>
                              );
                            } else {
                              // 未上传，显示上传按钮
                              return (
                                <TableCell key={col.key}>
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => handleOpenUploadModal(record.personId, record.personName, col.key as AssetType)}
                                  >
                                    <Upload className="h-4 w-4 mr-1" />
                                    上传文件
                                  </Button>
                                </TableCell>
                              );
                            }
                          }
                        })}
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 border rounded-md">
                <div className="text-muted-foreground">暂无资产数据</div>
                <div className="text-sm text-muted-foreground mt-1">
                  点击"上传文件"按钮为残疾人上传资产文件
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 上传弹窗 */}
      <Dialog open={uploadModalOpen} onOpenChange={setUploadModalOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              上传{currentAsset ? ASSET_TYPE_LABELS[currentAsset.assetType] : ''} - {currentAsset?.personName}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label>文件类型</Label>
              <RadioGroup
                value={uploadFileType}
                onValueChange={(value) => setUploadFileType(value as AssetFileType)}
                className="flex space-x-2"
              >
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value={AssetFileType.IMAGE} id="image" />
                  <Label htmlFor="image">图片</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value={AssetFileType.VIDEO} id="video" />
                  <Label htmlFor="video">视频</Label>
                </div>
              </RadioGroup>
            </div>

            <div className="space-y-2">
              <Label>选择文件</Label>
              <FileSelector
                value={selectedFileId}
                onChange={handleFileChange}
                accept={uploadFileType === AssetFileType.IMAGE ? "image/*" : "video/*"}
                filterType={uploadFileType === AssetFileType.IMAGE ? "image" : "video"}
                placeholder="选择或上传文件"
                title="选择资产文件"
                description={uploadFileType === AssetFileType.IMAGE
                  ? "支持上传图片文件，文件大小不超过2MB"
                  : "支持上传视频文件，文件大小不超过50MB"}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setUploadModalOpen(false)}>
              取消
            </Button>
            <Button
              onClick={handleUpload}
              disabled={!selectedFileId || uploading}
            >
              {uploading ? '提交中...' : '提交'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 预览弹窗 */}
      <Dialog open={previewModalOpen} onOpenChange={setPreviewModalOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              {currentAsset ? ASSET_TYPE_LABELS[currentAsset.assetType] : ''} - {currentAsset?.personName}
            </DialogTitle>
          </DialogHeader>

          {currentAsset?.assetItem && (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>文件类型</Label>
                <Badge variant="outline">
                  {currentAsset.assetItem.assetFileType === AssetFileType.IMAGE ? '图片' : '视频'}
                </Badge>
              </div>

              <div className="space-y-2">
                <Label>关联时间</Label>
                <div>{new Date(currentAsset.assetItem.relatedTime).toLocaleDateString()}</div>
              </div>

              {currentAsset.assetItem.remark && (
                <div className="space-y-2">
                  <Label>备注</Label>
                  <div className="text-sm text-muted-foreground">{currentAsset.assetItem.remark}</div>
                </div>
              )}

              <div className="space-y-2">
                <Label>文件预览</Label>
                <div className="border rounded-md p-4 text-center">
                  {currentAsset.assetItem.file?.fullUrl ? (
                    currentAsset.assetItem.assetFileType === AssetFileType.IMAGE ? (
                      <img
                        src={currentAsset.assetItem.file.fullUrl}
                        alt="资产文件"
                        className="max-w-full h-auto max-h-[200px] mx-auto"
                      />
                    ) : (
                      <video
                        src={currentAsset.assetItem.file.fullUrl}
                        controls
                        className="max-w-full h-auto max-h-[200px] mx-auto"
                      />
                    )
                  ) : (
                    <div className="text-muted-foreground py-8">
                      无法加载文件预览，文件URL不可用
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          <DialogFooter className="flex justify-between">
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={!currentAsset?.assetItem}
            >
              <X className="h-4 w-4 mr-1" />
              删除
            </Button>
            <div className="flex space-x-2">
              <Button variant="outline" onClick={() => setPreviewModalOpen(false)}>
                关闭
              </Button>
              <Button onClick={() => {
                setPreviewModalOpen(false);
                setUploadModalOpen(true);
              }}>
                更新文件
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default OrderAssetModal;