'use client';

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

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

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

const STATUS_LABELS: Record<FertilizationPlan['spread_status'], string> = {
  unspread: '未散布',
  partial: '一部散布',
  completed: '散布済み',
  over_applied: '超過散布',
};

const STATUS_CLASSES: Record<FertilizationPlan['spread_status'], string> = {
  unspread: 'bg-gray-100 text-gray-700',
  partial: 'bg-amber-100 text-amber-800',
  completed: 'bg-emerald-100 text-emerald-800',
  over_applied: 'bg-rose-100 text-rose-800',
};

export default function FertilizerPage() {
  const router = useRouter();
  const [year, setYear] = useState<number>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('fertilizerYear');
      if (saved) return parseInt(saved, 10);
    }
    return currentYear;
  });
  const [plans, setPlans] = useState<FertilizationPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [mergeSourcePlan, setMergeSourcePlan] = useState<FertilizationPlan | null>(null);
  const [mergeTargets, setMergeTargets] = useState<
    { id: number; name: string; field_count: number; planned_total_bags: string; is_confirmed: boolean }[]
  >([]);
  const [mergeTargetId, setMergeTargetId] = useState<number | ''>('');
  const [mergeLoading, setMergeLoading] = useState(false);
  const [mergeSubmitting, setMergeSubmitting] = useState(false);
  const [mergeError, setMergeError] = useState<string | null>(null);

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

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

  const handleDelete = async (id: number, name: string) => {
    setError(null);
    try {
      await api.delete(`/fertilizer/plans/${id}/`);
      await fetchPlans();
    } catch (e) {
      console.error(e);
      setError(`「${name}」の削除に失敗しました。`);
    }
  };

  const handlePdf = async (id: number, name: string) => {
    setError(null);
    try {
      const res = await api.get(`/fertilizer/plans/${id}/pdf/`, { responseType: 'blob' });
      const url = URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
      const a = document.createElement('a');
      a.href = url;
      a.download = `施肥計画_${year}_${name}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      console.error(e);
      setError('PDF出力に失敗しました。');
    }
  };

  const openMergeDialog = async (plan: FertilizationPlan) => {
    setMergeSourcePlan(plan);
    setMergeTargets([]);
    setMergeTargetId('');
    setMergeError(null);
    setMergeLoading(true);
    try {
      const res = await api.get(`/fertilizer/plans/${plan.id}/merge_targets/`);
      setMergeTargets(res.data);
    } catch (e) {
      console.error(e);
      setMergeError('マージ先候補の読み込みに失敗しました。');
    } finally {
      setMergeLoading(false);
    }
  };

  const closeMergeDialog = () => {
    if (mergeSubmitting) return;
    setMergeSourcePlan(null);
    setMergeTargets([]);
    setMergeTargetId('');
    setMergeError(null);
    setMergeLoading(false);
  };

  const handleMerge = async () => {
    if (!mergeSourcePlan || !mergeTargetId) {
      setMergeError('マージ先の施肥計画を選択してください。');
      return;
    }
    setMergeSubmitting(true);
    setMergeError(null);
    try {
      await api.post(`/fertilizer/plans/${mergeSourcePlan.id}/merge_into/`, {
        target_plan_id: mergeTargetId,
      });
      closeMergeDialog();
      await fetchPlans();
    } catch (e: unknown) {
      const err = e as {
        response?: {
          data?: {
            error?: string;
            conflicts?: { field_name: string; fertilizer_name: string }[];
          };
        };
      };
      const conflicts = err.response?.data?.conflicts ?? [];
      if (conflicts.length > 0) {
        const details = conflicts
          .map((conflict) => `${conflict.field_name} × ${conflict.fertilizer_name}`)
          .join('、');
        setMergeError(`${err.response?.data?.error ?? '競合があるためマージできません。'} ${details}`);
      } else {
        setMergeError(err.response?.data?.error ?? 'マージに失敗しました。');
      }
    } finally {
      setMergeSubmitting(false);
    }
  };

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

  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-green-600" />
            <h1 className="text-2xl font-bold text-gray-800">施肥計画</h1>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={() => router.push('/workrecords')}
              className="flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              <NotebookText className="h-4 w-4" />
              作業記録
            </button>
            <button
              onClick={() => router.push('/fertilizer/spreading')}
              className="flex items-center gap-2 rounded-lg border border-emerald-300 px-4 py-2 text-sm text-emerald-700 hover:bg-emerald-50"
            >
              <Truck className="h-4 w-4" />
              散布実績
            </button>
            <button
              onClick={() => router.push('/fertilizer/masters')}
              className="rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
            >
              肥料マスタ
            </button>
            <button
              onClick={() => router.push('/fertilizer/new')}
              className="flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-white hover:bg-green-700"
            >
              <Plus className="h-4 w-4" />
              新規作成
            </button>
          </div>
        </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-green-500"
          >
            {years.map((y) => (
              <option key={y} value={y}>
                {y}年度
              </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>
            <button
              onClick={() => router.push('/fertilizer/new')}
              className="mt-4 rounded-lg bg-green-600 px-4 py-2 text-sm text-white hover:bg-green-700"
            >
              最初の計画を作成する
            </button>
          </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-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.crop_name} / {plan.variety_name}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-medium ${STATUS_CLASSES[plan.spread_status]}`}>
                        {STATUS_LABELS[plan.spread_status]}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right tabular-nums text-gray-600">{plan.planned_total_bags}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-gray-600">{plan.spread_total_bags}</td>
                    <td className="px-4 py-3 text-right tabular-nums text-gray-600">{plan.remaining_total_bags}</td>
                    <td className="px-4 py-3 text-right text-gray-600">{plan.field_count}筆</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handlePdf(plan.id, plan.name)}
                          className="flex items-center gap-1 rounded border border-gray-300 px-2.5 py-1.5 text-xs text-gray-700 hover:bg-gray-100"
                          title="PDF出力"
                        >
                          <FileDown className="h-3.5 w-3.5" />
                          PDF
                        </button>
                        <button
                          onClick={() => router.push(`/fertilizer/${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"
                          title="編集"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                          編集
                        </button>
                        {plan.is_variety_change_plan && (
                          <button
                            onClick={() => openMergeDialog(plan)}
                            className="flex items-center gap-1 rounded border border-emerald-300 px-2.5 py-1.5 text-xs text-emerald-700 hover:bg-emerald-50"
                            title="既存計画へマージ"
                          >
                            <GitMerge 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"
                          title="削除"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                          削除
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {mergeSourcePlan && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
          <div className="w-full max-w-xl rounded-lg bg-white shadow-xl">
            <div className="flex items-center justify-between border-b px-5 py-4">
              <div>
                <h2 className="text-lg font-semibold text-gray-800">既存計画へマージ</h2>
                <p className="mt-1 text-sm text-gray-500">{mergeSourcePlan.name}</p>
              </div>
              <button onClick={closeMergeDialog} className="text-gray-400 hover:text-gray-600">
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="space-y-4 px-5 py-4">
              <p className="text-sm text-gray-600">
                同年度・同品種の既存施肥計画へ統合します。競合する圃場 × 肥料がある場合はマージせず停止します。
              </p>

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

              {mergeLoading ? (
                <p className="text-sm text-gray-500">候補を読み込み中...</p>
              ) : mergeTargets.length === 0 ? (
                <p className="text-sm text-gray-500">マージ可能な施肥計画がありません。</p>
              ) : (
                <div className="space-y-2">
                  {mergeTargets.map((target) => (
                    <label
                      key={target.id}
                      className={`flex cursor-pointer items-start gap-3 rounded-lg border px-4 py-3 ${
                        target.is_confirmed ? 'border-gray-200 bg-gray-50 text-gray-400' : 'border-gray-300'
                      }`}
                    >
                      <input
                        type="radio"
                        name="merge-target"
                        value={target.id}
                        checked={mergeTargetId === target.id}
                        onChange={() => setMergeTargetId(target.id)}
                        disabled={target.is_confirmed}
                        className="mt-1"
                      />
                      <div className="min-w-0 flex-1">
                        <div className="font-medium text-gray-800">{target.name}</div>
                        <div className="mt-1 text-xs text-gray-500">
                          {target.field_count}筆 / 計画 {target.planned_total_bags}袋
                          {target.is_confirmed ? ' / 散布確定済みのため選択不可' : ''}
                        </div>
                      </div>
                    </label>
                  ))}
                </div>
              )}
            </div>

            <div className="flex items-center justify-end gap-3 border-t px-5 py-4">
              <button
                onClick={closeMergeDialog}
                disabled={mergeSubmitting}
                className="rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 disabled:opacity-50"
              >
                キャンセル
              </button>
              <button
                onClick={handleMerge}
                disabled={mergeSubmitting || mergeLoading || !mergeTargetId}
                className="rounded-lg bg-emerald-600 px-4 py-2 text-sm text-white hover:bg-emerald-700 disabled:opacity-50"
              >
                {mergeSubmitting ? 'マージ中...' : 'マージ実行'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
