import { useState, useEffect } from 'react';
import { Drawer, Upload, Form, Input, Select, Button, message, Progress, List, Tag } from 'antd';
import { InboxOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { mediaApi } from '@/lib/media-api';
import type { PhotoAlbum } from '@/types/media';
import { getErrorMessage } from '@/utils/getErrorMessage';

const { Dragger } = Upload;

interface UploadPhotoDrawerProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  albumId?: number; // Pre-select album
}

interface UploadResult {
  filename: string;
  success: boolean;
  error?: string;
}

const ACCEPTED_TYPES = '.jpg,.jpeg,.png,.webp,.avif,.gif,.tiff,.tif,.heic,.heif';

export default function UploadPhotoDrawer({ open, onClose, onSuccess, albumId }: UploadPhotoDrawerProps) {
  const [form] = Form.useForm();
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [results, setResults] = useState<UploadResult[]>([]);
  const [albums, setAlbums] = useState<PhotoAlbum[]>([]);
  const [fileList, setFileList] = useState<any[]>([]);

  useEffect(() => {
    if (open) {
      fetchAlbums();
      setResults([]);
      setProgress(0);
      setFileList([]);
      form.resetFields();
      if (albumId) form.setFieldsValue({ albumId });
    }
  }, [open, albumId]);

  const fetchAlbums = async () => {
    try {
      const { data } = await mediaApi.get('/albums', { params: { limit: 200 } });
      setAlbums(data.albums || []);
    } catch {
      // Ignore
    }
  };

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('Select at least one photo');
      return;
    }

    const values = form.getFieldsValue();
    setUploading(true);
    setResults([]);

    const uploadResults: UploadResult[] = [];

    for (let i = 0; i < fileList.length; i++) {
      const file = fileList[i].originFileObj || fileList[i];
      const formData = new FormData();
      formData.append('file', file);
      if (values.title && fileList.length === 1) formData.append('title', values.title);
      if (values.producer) formData.append('producer', values.producer);
      if (values.creator) formData.append('creator', values.creator);
      if (values.albumId) formData.append('albumId', String(values.albumId));

      try {
        await mediaApi.post('/photos/upload', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        uploadResults.push({ filename: file.name, success: true });
      } catch (error: unknown) {
        uploadResults.push({
          filename: file.name,
          success: false,
          error: getErrorMessage(error, 'Upload failed'),
        });
      }

      setProgress(Math.round(((i + 1) / fileList.length) * 100));
      setResults([...uploadResults]);
    }

    setUploading(false);
    const successCount = uploadResults.filter(r => r.success).length;
    if (successCount > 0) {
      message.success(`Uploaded ${successCount} photo${successCount > 1 ? 's' : ''}`);
      onSuccess();
    }
    if (successCount < fileList.length) {
      message.error(`${fileList.length - successCount} upload(s) failed`);
    }
  };

  return (
    <Drawer
      title="Upload Photos"
      open={open}
      onClose={onClose}
      width={480}
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Button onClick={onClose}>Cancel</Button>
          <Button
            type="primary"
            onClick={handleUpload}
            loading={uploading}
            disabled={fileList.length === 0}
          >
            Upload {fileList.length > 0 ? `(${fileList.length})` : ''}
          </Button>
        </div>
      }
    >
      <Form form={form} layout="vertical">
        <Dragger
          accept={ACCEPTED_TYPES}
          multiple
          beforeUpload={() => false}
          fileList={fileList}
          onChange={({ fileList: fl }) => setFileList(fl)}
          style={{ marginBottom: 16 }}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">Click or drag photos here</p>
          <p className="ant-upload-hint">
            JPG, PNG, WebP, AVIF, GIF, TIFF, HEIC
          </p>
        </Dragger>

        {fileList.length === 1 && (
          <Form.Item name="title" label="Title">
            <Input placeholder="Photo title" />
          </Form.Item>
        )}

        <Form.Item name="producer" label="Producer">
          <Input placeholder="Producer name" />
        </Form.Item>

        <Form.Item name="creator" label="Creator">
          <Input placeholder="Creator name" />
        </Form.Item>

        <Form.Item name="albumId" label="Add to Album">
          <Select
            placeholder="No album"
            allowClear
            options={albums.map(a => ({
              value: a.id,
              label: `${a.title} (${a.photoCount} photos)`,
            }))}
          />
        </Form.Item>
      </Form>

      {uploading && <Progress percent={progress} style={{ marginBottom: 16 }} />}

      {results.length > 0 && (
        <List
          size="small"
          dataSource={results}
          renderItem={(item) => (
            <List.Item>
              {item.success ? (
                <Tag icon={<CheckCircleOutlined />} color="success">{item.filename}</Tag>
              ) : (
                <Tag icon={<CloseCircleOutlined />} color="error">
                  {item.filename}: {item.error}
                </Tag>
              )}
            </List.Item>
          )}
        />
      )}
    </Drawer>
  );
}
