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

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

interface Achievement {
  id: number;
  deputy_key: string;
  title_id: string;
  title_en: string;
  description_id: string;
  description_en: string;
  pdf_url: string;
  image_url: string;
  order_num: number;
}

export const AchievementManager: React.FC = () => {
  const [deputies, setDeputies] = useState<Deputy[]>([]);
  const [selectedDeputy, setSelectedDeputy] = useState<string>('secretariat');
  const [achievements, setAchievements] = useState<Achievement[]>([]);
  const [loading, setLoading] = useState(false);

  // Form State
  const [isEditing, setIsEditing] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [titleId, setTitleId] = useState('');
  const [titleEn, setTitleEn] = useState('');
  const [descId, setDescId] = useState('');
  const [descEn, setDescEn] = useState('');
  const [pdfUrl, setPdfUrl] = useState('');
  const [imageUrl, setImageUrl] = 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 loadAchievements = async (deputyKey: string) => {
    setLoading(true);
    try {
      const data = await fetchApi(`/achievements?deputy_key=${deputyKey}`);
      setAchievements(data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const resetForm = () => {
    setIsEditing(false);
    setEditId(null);
    setTitleId('');
    setTitleEn('');
    setDescId('');
    setDescEn('');
    setPdfUrl('');
    setImageUrl('');
    setOrderNum(achievements.length + 1);
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, targetField: 'pdf' | 'image') => {
    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 === 'pdf') {
        setPdfUrl(result.url);
      } else {
        setImageUrl(result.url);
      }
      setMessage(`File ${file.name} berhasil diunggah!`);
    } catch (err: any) {
      alert(err.message || 'Gagal mengunggah file.');
    } finally {
      setUploading(false);
    }
  };

  const handleEdit = (item: Achievement) => {
    setIsEditing(true);
    setEditId(item.id);
    setTitleId(item.title_id);
    setTitleEn(item.title_en || '');
    setDescId(item.description_id || '');
    setDescEn(item.description_en || '');
    setPdfUrl(item.pdf_url || '');
    setImageUrl(item.image_url || '');
    setOrderNum(item.order_num || 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

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

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

    try {
      const payload = {
        deputy_key: selectedDeputy,
        title_id: titleId,
        title_en: titleEn || titleId,
        description_id: descId,
        description_en: descEn || descId,
        pdf_url: pdfUrl,
        image_url: imageUrl,
        order_num: Number(orderNum),
      };

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

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

  return (
    <div>
      <div style={styles.headerRow}>
        <h1 style={{ fontSize: '22px', fontWeight: 700, margin: 0 }}>Kelola Capaian & Prestasi</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 Capaian / Laporan' : '➕ Tambah Capaian Baru'}
        </h3>
        <form onSubmit={handleSubmit} style={styles.form}>
          <div style={styles.row}>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>Judul Capaian (Bahasa Indonesia)</label>
              <input
                type="text"
                value={titleId}
                onChange={(e) => setTitleId(e.target.value)}
                placeholder="Masukkan judul capaian / prestasi"
                required
                style={styles.input}
              />
            </div>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>Judul Capaian (Bahasa Inggris)</label>
              <input
                type="text"
                value={titleEn}
                onChange={(e) => setTitleEn(e.target.value)}
                placeholder="Masukkan judul versi Inggris..."
                style={styles.input}
              />
            </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}>Deskripsi (Bahasa Indonesia)</label>
              <textarea
                rows={3}
                value={descId}
                onChange={(e) => setDescId(e.target.value)}
                placeholder="Ringkasan atau rincian capaian..."
                style={styles.textarea}
              />
            </div>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>Deskripsi (Bahasa Inggris)</label>
              <textarea
                rows={3}
                value={descEn}
                onChange={(e) => setDescEn(e.target.value)}
                placeholder="Description in English..."
                style={styles.textarea}
              />
            </div>
          </div>

          <div style={styles.row}>
            <div style={{ flex: 1 }}>
              <label style={styles.label}>File Laporan PDF (URL / Upload File)</label>
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  type="text"
                  value={pdfUrl}
                  onChange={(e) => setPdfUrl(e.target.value)}
                  placeholder="URL PDF Dokumen Laporan..."
                  style={{ ...styles.input, flex: 1 }}
                />
                <label style={styles.uploadBtn}>
                  📄 Unggah PDF
                  <input
                    type="file"
                    accept=".pdf"
                    onChange={(e) => handleFileUpload(e, 'pdf')}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
            </div>

            <div style={{ flex: 1 }}>
              <label style={styles.label}>Gambar Sampul (Opsional)</label>
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  type="text"
                  value={imageUrl}
                  onChange={(e) => setImageUrl(e.target.value)}
                  placeholder="URL Gambar Sampul..."
                  style={{ ...styles.input, flex: 1 }}
                />
                <label style={styles.uploadBtn}>
                  🖼️ Unggah Sampul
                  <input
                    type="file"
                    accept="image/*"
                    onChange={(e) => handleFileUpload(e, 'image')}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end', marginTop: '8px' }}>
            {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 Capaian'}
            </button>
          </div>
        </form>
      </div>

      {/* Achievements Table */}
      <div style={styles.tableCard}>
        <h3 style={{ margin: '0 0 16px 0' }}>Daftar Capaian ({achievements.length} item)</h3>
        {loading ? (
          <div style={{ color: '#94a3b8' }}>Memuat capaian...</div>
        ) : achievements.length === 0 ? (
          <div style={{ color: '#94a3b8' }}>Belum ada capaian untuk kedeputian ini.</div>
        ) : (
          <table style={styles.table}>
            <thead>
              <tr>
                <th style={{ ...styles.th, width: '60px' }}>No</th>
                <th style={styles.th}>Judul Capaian</th>
                <th style={styles.th}>File PDF</th>
                <th style={{ ...styles.th, width: '140px', textAlign: 'center' }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {achievements.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, fontWeight: 600 }}>{item.title_id}</td>
                  <td style={{ ...styles.td, fontSize: '13px', color: '#60a5fa' }}>{item.pdf_url || '-'}</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',
  },
  textarea: {
    width: '100%',
    padding: '10px 14px',
    borderRadius: '8px',
    border: '1px solid #475569',
    backgroundColor: '#0f172a',
    color: '#ffffff',
    fontSize: '14px',
    fontFamily: 'inherit',
    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',
  },
  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',
  },
};
