import React, { useState, useEffect } from 'react';
import { updateAsset } from '../../../services/assets-api';
import type { Asset } from '../../../types/assets';
import Modal from '../../../components/ui/Modal';
import Button from '../../../components/ui/Button';
import { useToast } from '../../../hooks/use-toast';

interface EditAssetModalProps {
  isOpen: boolean;
  onClose: () => void;
  asset: Asset | null;
  onSuccess: () => void;
}

export const EditAssetModal: React.FC<EditAssetModalProps> = ({
  isOpen,
  onClose,
  asset,
  onSuccess
}) => {
  const { success, error } = useToast();
  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editCategory, setEditCategory] = useState('Marketing');
  const [editSubcategory, setEditSubcategory] = useState('');
  const [editTags, setEditTags] = useState('');
  const [editGithubUrl, setEditGithubUrl] = useState('');
  const [editIsDownloadable, setEditIsDownloadable] = useState(true);
  const [isSavingEdit, setIsSavingEdit] = useState(false);

  useEffect(() => {
    if (asset) {
      setEditTitle(asset.title);
      setEditDescription(asset.description || '');
      setEditCategory(asset.categoryId || 'Marketing');
      setEditSubcategory(asset.subcategory || '');
      setEditTags(asset.tags.join(', '));
      setEditGithubUrl(asset.githubUrl || '');
      setEditIsDownloadable(asset.isDownloadable);
    }
  }, [asset]);

  const handleEditSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!asset) return;

    setIsSavingEdit(true);
    try {
      await updateAsset(asset.id, {
        title: editTitle,
        description: editDescription,
        categoryId: editCategory,
        subcategory: editSubcategory,
        tags: editTags.split(',').map(t => t.trim()).filter(Boolean),
        githubUrl: editGithubUrl,
        isDownloadable: editIsDownloadable,
      });
      success('Changes saved successfully', 'Asset details have been updated.');
      onSuccess();
      onClose();
    } catch (err: any) {
      console.error('Failed to save asset details', err);
      error('Failed to save changes', err.response?.data?.error || 'Something went wrong.');
    } finally {
      setIsSavingEdit(false);
    }
  };

  return (
    <Modal
      isOpen={isOpen && !!asset}
      onClose={onClose}
      title="Edit Asset Details"
      size="lg"
      footer={
        <>
          <Button
            type="button"
            onClick={onClose}
            variant="ghost"
            size="sm"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            form="edit-asset-form"
            disabled={isSavingEdit}
            variant="primary"
            size="sm"
          >
            {isSavingEdit ? 'Saving...' : 'Save Changes'}
          </Button>
        </>
      }
    >
      {asset && (
        <form id="edit-asset-form" onSubmit={handleEditSubmit} className="space-y-4">
          <div>
            <label className="text-xs font-semibold text-ink-500 mb-1.5 block">Asset Title</label>
            <input
              type="text"
              value={editTitle}
              onChange={(e) => setEditTitle(e.target.value)}
              required
              className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400"
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-semibold text-ink-500 mb-1.5 block">Category</label>
              <select
                value={editCategory}
                onChange={(e) => setEditCategory(e.target.value)}
                className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900"
              >
                <option value="Marketing">Marketing</option>
                <option value="Presentations">Presentations</option>
                <option value="Branding">Branding</option>
                <option value="Resources">Resources</option>
                <option value="Technical">Technical</option>
              </select>
            </div>
            <div>
              <label className="text-xs font-semibold text-ink-500 mb-1.5 block">Subcategory</label>
              <input
                type="text"
                value={editSubcategory}
                onChange={(e) => setEditSubcategory(e.target.value)}
                placeholder="e.g. Slide Deck"
                className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-semibold text-ink-500 mb-1.5 block">Description</label>
            <textarea
              value={editDescription}
              onChange={(e) => setEditDescription(e.target.value)}
              placeholder="Enter short description..."
              rows={3}
              className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 resize-none"
            />
          </div>

          {asset.type !== 'url' && (
            <div className="flex items-center gap-3 p-3 bg-ink-50 border border-ink-200 rounded-lg">
              <input
                type="checkbox"
                id="editIsDownloadable"
                checked={editIsDownloadable}
                onChange={(e) => setEditIsDownloadable(e.target.checked)}
                className="w-4 h-4 rounded border-ink-300 text-ink-900 focus:ring-ink-900/10 cursor-pointer"
              />
              <div>
                <label htmlFor="editIsDownloadable" className="text-xs font-bold text-ink-900 cursor-pointer block">
                  Allow Direct Download (Strict View Only if unchecked)
                </label>
                <span className="text-[10px] text-ink-500">
                  Toggle client authorization requirement for asset downloads.
                </span>
              </div>
            </div>
          )}

          <div>
            <label className="text-xs font-semibold text-ink-500 mb-1.5 block">Tags (comma-separated)</label>
            <input
              type="text"
              value={editTags}
              onChange={(e) => setEditTags(e.target.value)}
              placeholder="branding, guideline, pitch"
              className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-ink-500 mb-1.5 block">GitHub/Documentation URL (Optional)</label>
            <input
              type="url"
              value={editGithubUrl}
              onChange={(e) => setEditGithubUrl(e.target.value)}
              placeholder="https://github.com/..."
              className="w-full bg-ink-50 border border-ink-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400"
            />
          </div>
        </form>
      )}
    </Modal>
  );
};
