import { useEffect } from 'react';
import { Drawer, Form, Input, Select, Descriptions, message, Button } from 'antd';
import { mediaApi } from '@/lib/media-api';
import type { Photo } from '@/types/media';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface EditPhotoModalProps {
  photo: Photo | null;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export default function EditPhotoModal({ photo, open, onClose, onSuccess }: EditPhotoModalProps) {
  const [form] = Form.useForm();

  useEffect(() => {
    if (photo && open) {
      form.setFieldsValue({
        title: photo.title,
        description: photo.description,
        producer: photo.producer,
        creator: photo.creator,
        category: photo.category,
        tags: photo.tags || [],
        accessLevel: photo.accessLevel || 'free',
      });
    }
  }, [photo, open]);

  const handleSave = async () => {
    if (!photo) return;
    const values = form.getFieldsValue();
    try {
      await mediaApi.patch(`/photos/${photo.id}`, values);
      message.success('Photo updated');
      onSuccess();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to update photo'));
    }
  };

  if (!photo) return null;

  return (
    <Drawer
      title="Edit Photo"
      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={handleSave}>Save</Button>
        </div>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item name="title" label="Title">
          <Input />
        </Form.Item>
        <Form.Item name="description" label="Description">
          <Input.TextArea rows={3} />
        </Form.Item>
        <Form.Item name="producer" label="Producer">
          <Input />
        </Form.Item>
        <Form.Item name="creator" label="Creator">
          <Input />
        </Form.Item>
        <Form.Item name="category" label="Category">
          <Input placeholder="e.g. photos, events, portraits" />
        </Form.Item>
        <Form.Item name="tags" label="Tags">
          <Select mode="tags" placeholder="Add tags" />
        </Form.Item>
        <Form.Item name="accessLevel" label="Access Level">
          <Select
            options={[
              { value: 'free', label: 'Free' },
              { value: 'member', label: 'Member' },
              { value: 'premium', label: 'Premium' },
            ]}
          />
        </Form.Item>
      </Form>

      {/* EXIF Info (read-only) */}
      {(photo.cameraMake || photo.cameraModel || photo.takenAt) && (
        <Descriptions
          title="EXIF Data"
          size="small"
          column={1}
          bordered
          style={{ marginTop: 16 }}
        >
          {photo.cameraMake && (
            <Descriptions.Item label="Camera">{photo.cameraMake} {photo.cameraModel || ''}</Descriptions.Item>
          )}
          {photo.focalLength && (
            <Descriptions.Item label="Focal Length">{photo.focalLength}</Descriptions.Item>
          )}
          {photo.aperture && (
            <Descriptions.Item label="Aperture">{photo.aperture}</Descriptions.Item>
          )}
          {photo.shutterSpeed && (
            <Descriptions.Item label="Shutter">{photo.shutterSpeed}</Descriptions.Item>
          )}
          {photo.iso && (
            <Descriptions.Item label="ISO">{photo.iso}</Descriptions.Item>
          )}
          {photo.takenAt && (
            <Descriptions.Item label="Taken At">{new Date(photo.takenAt).toLocaleString()}</Descriptions.Item>
          )}
          {photo.gpsLatitude && photo.gpsLongitude && (
            <Descriptions.Item label="GPS">
              {photo.gpsLatitude.toFixed(6)}, {photo.gpsLongitude.toFixed(6)}
            </Descriptions.Item>
          )}
        </Descriptions>
      )}

      {/* Metadata */}
      <Descriptions
        title="File Info"
        size="small"
        column={1}
        bordered
        style={{ marginTop: 16 }}
      >
        <Descriptions.Item label="Dimensions">
          {photo.width}×{photo.height} ({photo.orientation})
        </Descriptions.Item>
        <Descriptions.Item label="Format">
          {photo.format?.toUpperCase()}
          {photo.hasAlpha ? ' (alpha)' : ''}
        </Descriptions.Item>
        {photo.colorSpace && (
          <Descriptions.Item label="Color Space">{photo.colorSpace}</Descriptions.Item>
        )}
        {photo.dpi && (
          <Descriptions.Item label="DPI">{photo.dpi}</Descriptions.Item>
        )}
        <Descriptions.Item label="Original">
          {photo.originalFilename}
        </Descriptions.Item>
      </Descriptions>
    </Drawer>
  );
}
