import React, { useEffect, useState } from 'react';
import { fetchApi, uploadFile } from '../../utils/api';

interface Deputy {
  key_name: string;
  title_id: string;
}

interface GalleryItem {
  id: number;
  deputy_key: string;
  type: 'photo' | 'video' | 'document';
  title: string;
  src: string;
  thumbnail: string;
  order_num: number;
}

export const GalleryManager: React.FC = () => {
  const [deputies, setDeputies] = useState<Deputy[]>([]);
  const [selectedDeputy, setSelectedDeputy] = useState<string>('secretariat');
  const [galleryList, setGalleryList] = useState<GalleryItem[]>([]);
  const [loading, setLoading] = useState(false);

  // Form State
  const [isEditing, setIsEditing] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [title, setTitle] = useState('');
  const [type, setType] = useState<'photo' | 'video' | 'document'>('photo');
  const [src, setSrc] = useState('');
  const [thumbnail, setThumbnail] = useState('');
  const [orderNum, setOrderNum] = useState(1);
  const [uploading, setUploading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');

  useEffect(() => {
    fetchApi('/deputies').then((data) => setDeputies(data)).catch(console.error);
  }, []);

  const loadGallery = async (deputyKey: string) => {
    setLoading(true);
    try {
      const data = await fetchApi(`/galleries?deputy_key=${deputyKey}`);
      setGalleryList(data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (selectedDeputy) {
      loadGallery(selectedDeputy);
    }
  }, [selectedDeputy]);

  const resetForm = () => {
    setIsEditing(false);
    setEditId(null);
    setTitle('');
    setType('photo');
    setSrc('');
    setThumbnail('');
    setOrderNum(galleryList.length + 1);
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, targetField: 'src' | 'thumbnail') => {
    if (!e.target.files || e.target.files.length === 0) return;
    const file = e.target.files[0];
    setUploading(true);

    try {
      const result = await uploadFile(file);
      if (targetField === 'src') {
        setSrc(result.url);
      } else {
        setThumbnail(result.url);
      }
      setMessage(`File ${file.name} berhasil diunggah!`);
    } catch (err: any) {
      alert(err.message || 'Gagal mengunggah file.');
    } finally {
      setUploading(false);
    }
  };

  const handleEdit = (item: GalleryItem) => {
    setIsEditing(true);
    setEditId(item.id);
    setTitle(item.title);
    setType(item.type);
    setSrc(item.src);
    setThumbnail(item.thumbnail || '');
    setOrderNum(item.order_num || 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Apakah Anda yakin ingin menghapus media galeri ini?')) return;
    try {
      await fetchApi(`/galleries/${id}`, { method: 'DELETE' });
      setMessage('Item galeri berhasil dihapus.');
      loadGallery(selectedDeputy);
    } catch (err: any) {
      alert(err.message || 'Gagal menghapus item galeri.');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage('');

    try {
      const payload = {
        deputy_key: selectedDeputy,
        type,
        title,
        src,
        thumbnail: thumbnail || src,
        order_num: Number(orderNum),
      };

      if (isEditing && editId) {
        await fetchApi(`/galleries/${editId}`, {
          method: 'PUT',
          body: JSON.stringify(payload),
        });
        setMessage('Item galeri berhasil diperbarui!');
      } else {
        await fetchApi('/galleries', {
          method: 'POST',
          body: JSON.stringify(payload),
        });
        setMessage('Item galeri baru berhasil ditambahkan!');
      }

      resetForm();
      loadGallery(selectedDeputy);
    } catch (err: any) {
      alert(err.message || 'Gagal menyimpan item galeri.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      <div style={styles.headerRow}>
        <h1 style={{ fontSize: '22px', fontWeight: 700, margin: 0 }}>Kelola Galeri & Media</h1>

        <select
          value={selectedDeputy}
          onChange={(e) => {
            setSelectedDeputy(e.target.value);
            resetForm();
          }}
          style={styles.select}
        >
          {deputies.map((d) => (
            <option key={d.key_name} value={d.key_name}>
              {d.title_id} ({d.key_name})
            </option>
          ))}
        </select>
      </div>

      {message && <div style={styles.successAlert}>{message}</div>}

      {/* Form Add/Edit */}
      <div style={styles.formCard}>
        <h3 style={{ margin: '0 0 16px 0', color: '#60a5fa' }}>
          {isEditing ? '✏️ Edit Media Galeri' : '➕ Tambah Media Baru'}
        </h3>
        <form onSubmit={handleSubmit} style={styles.form}>
          <div style={styles.row}>
            <div style={{ flex: 2 }}>
              <label style={styles.label}>Judul Media / Dokumen</label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Masukkan judul foto, video, atau dokumen"
                required
                style={styles.input}
              />
            </div>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>Tipe Media</label>
              <select
                value={type}
                onChange={(e) => setType(e.target.value as any)}
                style={styles.input}
              >
                <option value="photo">📷 Foto / Gambar</option>
                <option value="video">🎥 Video (MP4)</option>
                <option value="document">📄 Dokumen (PDF)</option>
              </select>
            </div>
            <div style={{ width: '100px' }}>
              <label style={styles.label}>Urutan</label>
              <input
                type="number"
                value={orderNum}
                onChange={(e) => setOrderNum(Number(e.target.value))}
                style={styles.input}
              />
            </div>
          </div>

          <div style={styles.row}>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>URL File Utama / Unggah File</label>
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  type="text"
                  value={src}
                  onChange={(e) => setSrc(e.target.value)}
                  placeholder="URL File atau upload dari komputer..."
                  required
                  style={{ ...styles.input, flex: 1 }}
                />
                <label style={styles.uploadBtn}>
                  {uploading ? 'Mengunggah...' : '📁 Pilih File'}
                  <input
                    type="file"
                    onChange={(e) => handleFileUpload(e, 'src')}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
            </div>

            <div style={{ flex: 1 }}>
              <label style={styles.label}>URL Sampul / Thumbnail (Opsional)</label>
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  type="text"
                  value={thumbnail}
                  onChange={(e) => setThumbnail(e.target.value)}
                  placeholder="URL Thumbnail gambar..."
                  style={{ ...styles.input, flex: 1 }}
                />
                <label style={styles.uploadBtn}>
                  📁 Pilih Thumbnail
                  <input
                    type="file"
                    accept="image/*"
                    onChange={(e) => handleFileUpload(e, 'thumbnail')}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
            {isEditing && (
              <button type="button" onClick={resetForm} style={styles.cancelBtn}>
                Batal
              </button>
            )}
            <button type="submit" disabled={saving || uploading} style={styles.saveBtn}>
              {saving ? 'Menyimpan...' : isEditing ? 'Simpan Perubahan' : 'Tambah Media'}
            </button>
          </div>
        </form>
      </div>

      {/* Gallery Table */}
      <div style={styles.tableCard}>
        <h3 style={{ margin: '0 0 16px 0' }}>Daftar Media Galeri ({galleryList.length} item)</h3>
        {loading ? (
          <div style={{ color: '#94a3b8' }}>Memuat media...</div>
        ) : galleryList.length === 0 ? (
          <div style={{ color: '#94a3b8' }}>Belum ada media galeri untuk kedeputian ini.</div>
        ) : (
          <table style={styles.table}>
            <thead>
              <tr>
                <th style={{ ...styles.th, width: '60px' }}>No</th>
                <th style={{ ...styles.th, width: '100px' }}>Tipe</th>
                <th style={styles.th}>Judul</th>
                <th style={styles.th}>File URL</th>
                <th style={{ ...styles.th, width: '140px', textAlign: 'center' }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {galleryList.map((item, idx) => (
                <tr key={item.id} style={styles.tr}>
                  <td style={{ ...styles.td, textAlign: 'center' }}>{item.order_num || idx + 1}</td>
                  <td style={styles.td}>
                    <span style={styles.badge}>
                      {item.type === 'photo' ? '📷 Foto' : item.type === 'video' ? '🎥 Video' : '📄 PDF'}
                    </span>
                  </td>
                  <td style={{ ...styles.td, fontWeight: 600 }}>{item.title}</td>
                  <td style={{ ...styles.td, fontSize: '12px', color: '#60a5fa' }}>{item.src}</td>
                  <td style={{ ...styles.td, textAlign: 'center' }}>
                    <button onClick={() => handleEdit(item)} style={styles.editBtn}>
                      Edit
                    </button>
                    <button onClick={() => handleDelete(item.id)} style={styles.deleteBtn}>
                      Hapus
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

const styles: { [key: string]: React.CSSProperties } = {
  headerRow: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px',
  },
  select: {
    padding: '10px 16px',
    borderRadius: '8px',
    backgroundColor: '#1e293b',
    color: '#ffffff',
    border: '1px solid #475569',
    fontSize: '14px',
    outline: 'none',
  },
  formCard: {
    backgroundColor: '#1e293b',
    borderRadius: '12px',
    padding: '24px',
    marginBottom: '32px',
    border: '1px solid #334155',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  row: {
    display: 'flex',
    gap: '16px',
  },
  label: {
    display: 'block',
    fontSize: '13px',
    fontWeight: 600,
    color: '#cbd5e1',
    marginBottom: '6px',
  },
  input: {
    width: '100%',
    padding: '10px 14px',
    borderRadius: '8px',
    border: '1px solid #475569',
    backgroundColor: '#0f172a',
    color: '#ffffff',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  uploadBtn: {
    padding: '10px 16px',
    borderRadius: '8px',
    backgroundColor: '#334155',
    color: '#ffffff',
    fontSize: '13px',
    fontWeight: 600,
    cursor: 'pointer',
    whiteSpace: 'nowrap',
    display: 'flex',
    alignItems: 'center',
  },
  saveBtn: {
    padding: '10px 24px',
    borderRadius: '8px',
    backgroundColor: '#2563eb',
    color: '#ffffff',
    border: 'none',
    fontWeight: 600,
    cursor: 'pointer',
  },
  cancelBtn: {
    padding: '10px 20px',
    borderRadius: '8px',
    backgroundColor: '#475569',
    color: '#ffffff',
    border: 'none',
    cursor: 'pointer',
  },
  tableCard: {
    backgroundColor: '#1e293b',
    borderRadius: '12px',
    padding: '24px',
    border: '1px solid #334155',
  },
  table: {
    width: '100%',
    borderCollapse: 'collapse',
    fontSize: '14px',
  },
  th: {
    backgroundColor: '#0f172a',
    padding: '12px 16px',
    textAlign: 'left',
    color: '#94a3b8',
    borderBottom: '1px solid #334155',
  },
  tr: {
    borderBottom: '1px solid #334155',
  },
  td: {
    padding: '12px 16px',
    color: '#e2e8f0',
  },
  badge: {
    backgroundColor: '#334155',
    padding: '4px 8px',
    borderRadius: '6px',
    fontSize: '12px',
    fontWeight: 600,
  },
  editBtn: {
    padding: '6px 12px',
    borderRadius: '6px',
    backgroundColor: '#d97706',
    color: '#ffffff',
    border: 'none',
    fontSize: '12px',
    fontWeight: 600,
    cursor: 'pointer',
    marginRight: '6px',
  },
  deleteBtn: {
    padding: '6px 12px',
    borderRadius: '6px',
    backgroundColor: '#dc2626',
    color: '#ffffff',
    border: 'none',
    fontSize: '12px',
    fontWeight: 600,
    cursor: 'pointer',
  },
  successAlert: {
    backgroundColor: '#064e3b',
    color: '#a7f3d0',
    padding: '12px 16px',
    borderRadius: '8px',
    marginBottom: '20px',
    fontSize: '14px',
    border: '1px solid #047857',
  },
};
