'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Pencil, Trash2, ChevronLeft, Check, X } from 'lucide-react';
import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';
import { Fertilizer } from '@/types';

const emptyForm = (): Omit<Fertilizer, 'id'> => ({
  name: '',
  maker: null,
  capacity_kg: null,
  nitrogen_pct: null,
  phosphorus_pct: null,
  potassium_pct: null,
  notes: null,
  material: null,
  material_id: null,
});

export default function FertilizerMastersPage() {
  const router = useRouter();
  const [fertilizers, setFertilizers] = useState<Fertilizer[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<number | 'new' | null>(null);
  const [form, setForm] = useState(emptyForm());
  const [saving, setSaving] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);

  useEffect(() => {
    fetchFertilizers();
  }, []);

  const fetchFertilizers = async () => {
    try {
      const res = await api.get('/fertilizer/fertilizers/');
      setFertilizers(res.data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  const startNew = () => {
    setForm(emptyForm());
    setEditingId('new');
  };

  const startEdit = (f: Fertilizer) => {
    setForm({
      name: f.name,
      maker: f.maker,
      capacity_kg: f.capacity_kg,
      nitrogen_pct: f.nitrogen_pct,
      phosphorus_pct: f.phosphorus_pct,
      potassium_pct: f.potassium_pct,
      notes: f.notes,
      material: f.material,
      material_id: f.material_id,
    });
    setEditingId(f.id);
  };

  const cancelEdit = () => {
    setEditingId(null);
    setForm(emptyForm());
  };

  const handleSave = async () => {
    if (!form.name.trim()) return alert('肥料名を入力してください');
    setSaving(true);
    try {
      const payload = {
        ...form,
        maker: form.maker || null,
        capacity_kg: form.capacity_kg || null,
        nitrogen_pct: form.nitrogen_pct || null,
        phosphorus_pct: form.phosphorus_pct || null,
        potassium_pct: form.potassium_pct || null,
        notes: form.notes || null,
      };
      if (editingId === 'new') {
        await api.post('/fertilizer/fertilizers/', payload);
      } else {
        await api.put(`/fertilizer/fertilizers/${editingId}/`, payload);
      }
      await fetchFertilizers();
      setEditingId(null);
    } catch (e: unknown) {
      const err = e as { response?: { data?: unknown } };
      console.error(err);
      alert('保存に失敗しました: ' + JSON.stringify(err.response?.data));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: number, name: string) => {
    setDeleteError(null);
    try {
      await api.delete(`/fertilizer/fertilizers/${id}/`);
      await fetchFertilizers();
    } catch (e) {
      console.error(e);
      setDeleteError(`「${name}」の削除に失敗しました（施肥計画で使用中の肥料は削除できません）`);
    }
  };

  const setField = (key: keyof typeof form, value: string) => {
    setForm((prev) => ({ ...prev, [key]: value || null }));
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-5xl mx-auto px-4 py-8">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <button
              onClick={() => router.push('/fertilizer')}
              className="text-gray-500 hover:text-gray-700"
            >
              <ChevronLeft className="h-5 w-5" />
            </button>
            <h1 className="text-2xl font-bold text-gray-800">肥料マスタ</h1>
          </div>
          <button
            onClick={startNew}
            disabled={editingId !== null}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
          >
            <Plus className="h-4 w-4" />
            新規追加
          </button>
        </div>

        {deleteError && (
          <div className="mb-4 flex items-start gap-2 bg-red-50 border border-red-300 text-red-700 rounded-lg px-4 py-3 text-sm">
            <span className="font-bold shrink-0">⚠</span>
            <span>{deleteError}</span>
            <button onClick={() => setDeleteError(null)} className="ml-auto shrink-0 text-red-400 hover:text-red-600">✕</button>
          </div>
        )}

        {loading ? (
          <p className="text-gray-500">読み込み中...</p>
        ) : (
          <div className="bg-white rounded-lg shadow overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b">
                <tr>
                  <th className="text-left px-4 py-3 font-medium text-gray-700">肥料名</th>
                  <th className="text-left px-4 py-3 font-medium text-gray-700">メーカー</th>
                  <th className="text-right px-4 py-3 font-medium text-gray-700">1袋(kg)</th>
                  <th className="text-right px-4 py-3 font-medium text-gray-700">窒素(%)</th>
                  <th className="text-right px-4 py-3 font-medium text-gray-700">リン酸(%)</th>
                  <th className="text-right px-4 py-3 font-medium text-gray-700">カリ(%)</th>
                  <th className="text-left px-4 py-3 font-medium text-gray-700">備考</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {editingId === 'new' && (
                  <EditRow
                    form={form}
                    setField={setField}
                    onSave={handleSave}
                    onCancel={cancelEdit}
                    saving={saving}
                  />
                )}
                {fertilizers.map((f) =>
                  editingId === f.id ? (
                    <EditRow
                      key={f.id}
                      form={form}
                      setField={setField}
                      onSave={handleSave}
                      onCancel={cancelEdit}
                      saving={saving}
                    />
                  ) : (
                    <tr key={f.id} className="hover:bg-gray-50">
                      <td className="px-4 py-3 font-medium">{f.name}</td>
                      <td className="px-4 py-3 text-gray-600">{f.maker ?? '-'}</td>
                      <td className="px-4 py-3 text-right text-gray-600">{f.capacity_kg ?? '-'}</td>
                      <td className="px-4 py-3 text-right text-gray-600">{f.nitrogen_pct ?? '-'}</td>
                      <td className="px-4 py-3 text-right text-gray-600">{f.phosphorus_pct ?? '-'}</td>
                      <td className="px-4 py-3 text-right text-gray-600">{f.potassium_pct ?? '-'}</td>
                      <td className="px-4 py-3 text-gray-600 max-w-xs truncate">{f.notes ?? '-'}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2 justify-end">
                          <button
                            onClick={() => startEdit(f)}
                            disabled={editingId !== null}
                            className="text-gray-400 hover:text-blue-600 disabled:opacity-30"
                          >
                            <Pencil className="h-4 w-4" />
                          </button>
                          <button
                            onClick={() => handleDelete(f.id, f.name)}
                            disabled={editingId !== null}
                            className="text-gray-400 hover:text-red-600 disabled:opacity-30"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                )}
                {fertilizers.length === 0 && editingId === null && (
                  <tr>
                    <td colSpan={8} className="px-4 py-8 text-center text-gray-400">
                      肥料が登録されていません
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function EditRow({
  form,
  setField,
  onSave,
  onCancel,
  saving,
}: {
  form: Omit<Fertilizer, 'id'>;
  setField: (key: keyof Omit<Fertilizer, 'id'>, value: string) => void;
  onSave: () => void;
  onCancel: () => void;
  saving: boolean;
}) {
  const inputCls = 'w-full border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-green-500';
  const numCls = inputCls + ' text-right';

  return (
    <tr className="bg-green-50">
      <td className="px-2 py-2">
        <input
          className={inputCls}
          value={form.name}
          onChange={(e) => setField('name', e.target.value)}
          placeholder="肥料名（必須）"
          autoFocus
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={inputCls}
          value={form.maker ?? ''}
          onChange={(e) => setField('maker', e.target.value)}
          placeholder="メーカー"
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={numCls}
          type="number"
          step="0.001"
          value={form.capacity_kg ?? ''}
          onChange={(e) => setField('capacity_kg', e.target.value)}
          placeholder="kg"
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={numCls}
          type="number"
          step="0.01"
          value={form.nitrogen_pct ?? ''}
          onChange={(e) => setField('nitrogen_pct', e.target.value)}
          placeholder="%"
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={numCls}
          type="number"
          step="0.01"
          value={form.phosphorus_pct ?? ''}
          onChange={(e) => setField('phosphorus_pct', e.target.value)}
          placeholder="%"
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={numCls}
          type="number"
          step="0.01"
          value={form.potassium_pct ?? ''}
          onChange={(e) => setField('potassium_pct', e.target.value)}
          placeholder="%"
        />
      </td>
      <td className="px-2 py-2">
        <input
          className={inputCls}
          value={form.notes ?? ''}
          onChange={(e) => setField('notes', e.target.value)}
          placeholder="備考"
        />
      </td>
      <td className="px-2 py-2">
        <div className="flex items-center gap-1 justify-end">
          <button
            onClick={onSave}
            disabled={saving}
            className="text-green-600 hover:text-green-800 disabled:opacity-50"
          >
            <Check className="h-4 w-4" />
          </button>
          <button onClick={onCancel} className="text-gray-400 hover:text-gray-600">
            <X className="h-4 w-4" />
          </button>
        </div>
      </td>
    </tr>
  );
}
