'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Pencil, Plus, Sprout, Trash2 } from 'lucide-react';

import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';
import { RiceTransplantPlan } from '@/types';

const currentYear = new Date().getFullYear();

export default function RiceTransplantPage() {
  const router = useRouter();
  const [year, setYear] = useState<number>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('riceTransplantYear');
      if (saved) return parseInt(saved, 10);
    }
    return currentYear;
  });
  const [plans, setPlans] = useState<RiceTransplantPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const years = Array.from({ length: 5 }, (_, i) => currentYear + 1 - i);

  const fetchPlans = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await api.get(`/plans/rice-transplant-plans/?year=${year}`);
      setPlans(res.data);
    } catch (e) {
      console.error(e);
      setError('田植え計画の読み込みに失敗しました。');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    localStorage.setItem('riceTransplantYear', String(year));
    fetchPlans();
  }, [year]);

  const handleDelete = async (id: number, name: string) => {
    setError(null);
    if (!confirm(`「${name}」を削除しますか？`)) {
      return;
    }
    try {
      await api.delete(`/plans/rice-transplant-plans/${id}/`);
      await fetchPlans();
    } catch (e) {
      console.error(e);
      setError(`「${name}」の削除に失敗しました。`);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="mx-auto max-w-6xl px-4 py-8">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Sprout className="h-6 w-6 text-emerald-600" />
            <h1 className="text-2xl font-bold text-gray-800">田植え計画</h1>
          </div>
          <button
            onClick={() => router.push('/rice-transplant/new')}
            className="flex items-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-white hover:bg-emerald-700"
          >
            <Plus className="h-4 w-4" />
            新規作成
          </button>
        </div>

        <div className="mb-6 flex items-center gap-3">
          <label className="text-sm font-medium text-gray-700">年度:</label>
          <select
            value={year}
            onChange={(e) => setYear(parseInt(e.target.value, 10))}
            className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
          >
            {years.map((value) => (
              <option key={value} value={value}>
                {value}年度
              </option>
            ))}
          </select>
        </div>

        {error && (
          <div className="mb-4 rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-700">
            {error}
          </div>
        )}

        {loading ? (
          <p className="text-gray-500">読み込み中...</p>
        ) : plans.length === 0 ? (
          <div className="rounded-lg bg-white p-12 text-center text-gray-400 shadow">
            <Sprout className="mx-auto mb-3 h-12 w-12 opacity-30" />
            <p>{year}年度の田植え計画はありません</p>
          </div>
        ) : (
          <div className="overflow-hidden rounded-lg bg-white shadow">
            <table className="w-full text-sm">
              <thead className="border-b bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left font-medium text-gray-700">計画名</th>
                  <th className="px-4 py-3 text-left font-medium text-gray-700">種子資材</th>
                  <th className="px-4 py-3 text-right font-medium text-gray-700">圃場</th>
                  <th className="px-4 py-3 text-right font-medium text-gray-700">苗箱合計</th>
                  <th className="px-4 py-3 text-right font-medium text-gray-700">種もみ計画</th>
                  <th className="px-4 py-3 text-right font-medium text-gray-700">残在庫見込み</th>
                  <th className="px-4 py-3" />
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {plans.map((plan) => (
                  <tr key={plan.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3 font-medium text-gray-900">{plan.name}</td>
                    <td className="px-4 py-3 text-gray-600">
                      {plan.seed_material_name || '-'}
                    </td>
                    <td className="px-4 py-3 text-right text-gray-600">{plan.field_count}筆</td>
                    <td className="px-4 py-3 text-right tabular-nums text-gray-600">{plan.total_seedling_boxes}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-gray-600">{plan.total_seed_kg}kg</td>
                    <td className={`px-4 py-3 text-right tabular-nums ${parseFloat(plan.remaining_seed_kg) < 0 ? 'text-red-600' : 'text-emerald-700'}`}>
                      {plan.remaining_seed_kg}kg
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => router.push(`/rice-transplant/${plan.id}/edit`)}
                          className="flex items-center gap-1 rounded border border-blue-300 px-2.5 py-1.5 text-xs text-blue-700 hover:bg-blue-50"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                          編集
                        </button>
                        <button
                          onClick={() => handleDelete(plan.id, plan.name)}
                          className="flex items-center gap-1 rounded border border-red-300 px-2.5 py-1.5 text-xs text-red-600 hover:bg-red-50"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                          削除
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
