import React, { useState, useEffect } from 'react';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import { Plus, Trash2, Image as ImageIcon } from 'lucide-react';
import { FileSelector } from '@d8d/file-management-ui/components';
import { toast } from 'sonner';

export interface PhotoItem {
  photoType: string;
  fileId: number | null;
  canDownload: number;
  tempId?: string; // 临时ID用于React key
}

export interface PhotoUploadFieldProps {
  value?: PhotoItem[];
  onChange?: (photos: PhotoItem[]) => void;
  photoTypes?: string[];
  maxPhotos?: number;
}

export const PhotoUploadField: React.FC<PhotoUploadFieldProps> = ({
  value = [],
  onChange,
  photoTypes = ['身份证照片', '残疾证照片', '个人照片', '其他照片'],
  maxPhotos = undefined,
}) => {
  const [photos, setPhotos] = useState<PhotoItem[]>(value);

  // 同步外部value变化
  useEffect(() => {
    setPhotos(value);
  }, [value]);

  const handleAddPhoto = () => {
    if (maxPhotos !== undefined && photos.length >= maxPhotos) {
      toast.warning(`最多只能上传 ${maxPhotos} 张照片`);
      return;
    }

    const newPhoto: PhotoItem = {
      photoType: photoTypes[0],
      fileId: null,
      canDownload: 0,
      tempId: `temp-${Date.now()}-${Math.random()}`,
    };

    const newPhotos = [...photos, newPhoto];
    setPhotos(newPhotos);
    onChange?.(newPhotos);
  };

  const handleRemovePhoto = (index: number) => {
    const newPhotos = photos.filter((_, i) => i !== index);
    setPhotos(newPhotos);
    onChange?.(newPhotos);
  };

  const handlePhotoTypeChange = (index: number, photoType: string) => {
    const newPhotos = [...photos];
    newPhotos[index] = { ...newPhotos[index], photoType };
    setPhotos(newPhotos);
    onChange?.(newPhotos);
  };

  const handleFileIdChange = (index: number, fileId: number | null) => {
    const newPhotos = [...photos];
    newPhotos[index] = { ...newPhotos[index], fileId };
    setPhotos(newPhotos);
    onChange?.(newPhotos);
  };

  const handleCanDownloadChange = (index: number, canDownload: number) => {
    const newPhotos = [...photos];
    newPhotos[index] = { ...newPhotos[index], canDownload };
    setPhotos(newPhotos);
    onChange?.(newPhotos);
  };

  const getPhotoTypeLabel = (photoType: string) => {
    return photoType;
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label>照片上传</Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddPhoto}
          disabled={maxPhotos !== undefined && photos.length >= maxPhotos}
          data-testid="add-photo-button"
        >
          <Plus className="h-4 w-4 mr-2" />
          添加照片
        </Button>
      </div>

      {photos.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-8">
            <ImageIcon className="h-12 w-12 text-gray-400 mb-4" />
            <p className="text-gray-600 mb-2">暂无照片</p>
            <p className="text-sm text-gray-500 mb-4">点击"添加照片"按钮上传照片</p>
            <Button type="button" variant="outline" onClick={handleAddPhoto}>
              <Plus className="h-4 w-4 mr-2" />
              添加第一张照片
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {photos.map((photo, index) => (
            <Card key={photo.tempId || index} className="overflow-hidden">
              <CardContent className="p-4">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center space-x-2">
                    <div className="bg-primary/10 text-primary rounded-full w-6 h-6 flex items-center justify-center text-sm font-medium">
                      {index + 1}
                    </div>
                    <h4 className="font-medium">照片 {index + 1}</h4>
                  </div>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemovePhoto(index)}
                    className="text-red-500 hover:text-red-700 hover:bg-red-50"
                    data-testid={`remove-photo-button-${index}`}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 照片类型选择 */}
                  <div className="space-y-2">
                    <Label htmlFor={`photo-type-${index}`}>照片类型</Label>
                    <Select
                      value={photo.photoType}
                      onValueChange={(value) => handlePhotoTypeChange(index, value)}
                    >
                      <SelectTrigger id={`photo-type-${index}`}>
                        <SelectValue placeholder="选择照片类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {photoTypes.map((type) => (
                          <SelectItem key={type} value={type}>
                            {getPhotoTypeLabel(type)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 文件选择器 */}
                  <div className="space-y-2">
                    <Label>照片文件</Label>
                    <FileSelector
                      value={photo.fileId}
                      onChange={(fileId) => handleFileIdChange(index, fileId as number | null)}
                      accept="image/*,.jpg,.jpeg,.png,.gif,.bmp,.webp"
                      filterType="all"
                      placeholder="选择或上传照片"
                      showPreview={true}
                      previewSize="medium"
                    />
                  </div>

                  {/* 是否可下载开关 */}
                  <div className="flex items-center space-x-2">
                    <Switch
                      id={`can-download-${index}`}
                      checked={photo.canDownload === 1}
                      onCheckedChange={(checked) => handleCanDownloadChange(index, checked ? 1 : 0)}
                    />
                    <Label htmlFor={`can-download-${index}`}>允许下载</Label>
                  </div>
                </div>

                {/* 验证提示 */}
                {!photo.fileId && (
                  <p className="text-sm text-amber-600 mt-2">
                    请选择照片文件
                  </p>
                )}
              </CardContent>
            </Card>
          ))}

          {maxPhotos === undefined || photos.length < maxPhotos ? (
            <div className="text-center">
              <Button
                type="button"
                variant="outline"
                onClick={handleAddPhoto}
                className="w-full"
              >
                <Plus className="h-4 w-4 mr-2" />
                {maxPhotos !== undefined
                  ? `添加更多照片（${photos.length}/${maxPhotos}）`
                  : '添加更多照片'}
              </Button>
            </div>
          ) : null}
        </div>
      )}

      <div className="text-sm text-muted-foreground">
        {maxPhotos !== undefined && <p>• 最多可上传 {maxPhotos} 张照片</p>}
        <p>• 每张照片需要上传文件</p>
        <p>• 支持的照片格式：JPG、JPEG、PNG、GIF、BMP、WebP等常见图片格式</p>
        <p>• 文件大小限制：无限制（建议不超过500MB）</p>
      </div>
    </div>
  );
};

export default PhotoUploadField;