'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { api } from '@/lib/api';
import { Field, OfficialKyosaiField, OfficialChusankanField } from '@/types';
import Navbar from '@/components/Navbar';
import LinkModal from '@/components/LinkModal';
import { ArrowLeft, Save, Plus, X } from 'lucide-react';
export default function EditFieldPage() {
  const router = useRouter();
  const params = useParams();
  const fieldId = parseInt(params.id as string);

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [notFound, setNotFound] = useState(false);

  const [formData, setFormData] = useState({
    name: '',
    address: '',
    area_tan: '',
    area_m2: '',
    owner_name: '',
    group_name: '',
  });
  const [kyosaiFields, setKyosaiFields] = useState<OfficialKyosaiField[]>([]);
  const [chusankanFields, setChusankanFields] = useState<OfficialChusankanField[]>([]);

  // Modal state
  const [showKyosaiModal, setShowKyosaiModal] = useState(false);
  const [showChusankanModal, setShowChusankanModal] = useState(false);
  const [allKyosai, setAllKyosai] = useState<OfficialKyosaiField[]>([]);
  const [allChusankan, setAllChusankan] = useState<OfficialChusankanField[]>([]);

  useEffect(() => {
    fetchField();
  }, [fieldId]);

  const fetchField = async () => {
    try {
      const response = await api.get(`/fields/${fieldId}/`);
      const field: Field = response.data;
      setFormData({
        name: field.name || '',
        address: field.address || '',
        area_tan: field.area_tan?.toString() || '',
        area_m2: field.area_m2?.toString() || '',
        owner_name: field.owner_name || '',
        group_name: field.group_name || '',
      });
      setKyosaiFields(field.kyosai_fields || []);
      setChusankanFields(field.chusankan_fields || []);
    } catch (err: unknown) {
      console.error('Failed to fetch field:', err);
      const axiosError = err as { response?: { status?: number } };
      if (axiosError.response?.status === 404) {
        setNotFound(true);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

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

    try {
      const data = {
        name: formData.name,
        address: formData.address || null,
        area_tan: formData.area_tan ? parseFloat(formData.area_tan) : null,
        area_m2: formData.area_m2 ? parseInt(formData.area_m2) : null,
        owner_name: formData.owner_name || null,
        group_name: formData.group_name || null,
      };

      await api.patch(`/fields/${fieldId}/`, data);
      router.push('/fields');
    } catch (err: unknown) {
      console.error('Failed to update field:', err);
      setError('保存に失敗しました');
    } finally {
      setSaving(false);
    }
  };

  // --- Kyosai link management ---
  const openKyosaiModal = async () => {
    try {
      const res = await api.get('/kyosai-fields/');
      setAllKyosai(res.data);
      setShowKyosaiModal(true);
    } catch (err) {
      console.error('Failed to fetch kyosai fields:', err);
    }
  };

  const addKyosaiLinks = async (ids: number[]) => {
    try {
      await api.post(`/fields/${fieldId}/kyosai-links/`, { kyosai_field_ids: ids });
      await fetchField();
    } catch (err) {
      console.error('Failed to add kyosai links:', err);
    }
  };

  const removeKyosaiLink = async (kyosaiId: number) => {
    if (!confirm('この共済区画の紐づけを解除しますか？')) return;
    try {
      await api.delete(`/fields/${fieldId}/kyosai-links/${kyosaiId}/`);
      await fetchField();
    } catch (err) {
      console.error('Failed to remove kyosai link:', err);
    }
  };

  // --- Chusankan link management ---
  const openChusankanModal = async () => {
    try {
      const res = await api.get('/chusankan-fields/');
      setAllChusankan(res.data);
      setShowChusankanModal(true);
    } catch (err) {
      console.error('Failed to fetch chusankan fields:', err);
    }
  };

  const addChusankanLinks = async (ids: number[]) => {
    try {
      await api.post(`/fields/${fieldId}/chusankan-links/`, { chusankan_field_ids: ids });
      await fetchField();
    } catch (err) {
      console.error('Failed to add chusankan links:', err);
    }
  };

  const removeChusankanLink = async (chusankanId: number) => {
    if (!confirm('この中山間区画の紐づけを解除しますか？')) return;
    try {
      await api.delete(`/fields/${fieldId}/chusankan-links/${chusankanId}/`);
      await fetchField();
    } catch (err) {
      console.error('Failed to remove chusankan link:', err);
    }
  };

  // --- Computed ---
  const kyosaiLinkedIds = useMemo(() => new Set(kyosaiFields.map((k) => k.id)), [kyosaiFields]);
  const chusankanLinkedIds = useMemo(() => new Set(chusankanFields.map((c) => c.id)), [chusankanFields]);
  const kyosaiTotalArea = kyosaiFields.reduce((sum, k) => sum + k.area, 0);
  const chusankanTotalArea = chusankanFields.reduce((sum, c) => sum + c.area, 0);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navbar />
        <div className="flex items-center justify-center h-64">
          <div className="text-gray-500">読み込み中...</div>
        </div>
      </div>
    );
  }

  if (notFound) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Navbar />
        <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="bg-white rounded-lg shadow p-8 text-center">
            <p className="text-gray-500">圃場が見つかりません。</p>
            <button
              onClick={() => router.push('/fields')}
              className="mt-4 text-green-600 hover:text-green-700"
            >
              一覧に戻る
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-6">
          <button
            onClick={() => router.push('/fields')}
            className="flex items-center text-gray-600 hover:text-gray-900"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            一覧に戻る
          </button>
        </div>

        {/* 基本情報フォーム */}
        <div className="bg-white rounded-lg shadow p-6">
          <h1 className="text-2xl font-bold text-gray-900 mb-6">圃場編集</h1>

          {error && (
            <div className="mb-4 p-3 text-sm text-red-600 bg-red-50 rounded-md">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                  圃場名 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  required
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
              <div>
                <label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
                  住所
                </label>
                <input
                  type="text"
                  id="address"
                  name="address"
                  value={formData.address}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <div>
                <label htmlFor="area_tan" className="block text-sm font-medium text-gray-700 mb-1">
                  面積(反)
                </label>
                <input
                  type="number"
                  step="0.0001"
                  id="area_tan"
                  name="area_tan"
                  value={formData.area_tan}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
              <div>
                <label htmlFor="area_m2" className="block text-sm font-medium text-gray-700 mb-1">
                  面積(m2)
                </label>
                <input
                  type="number"
                  id="area_m2"
                  name="area_m2"
                  value={formData.area_m2}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
              <div>
                <label htmlFor="owner_name" className="block text-sm font-medium text-gray-700 mb-1">
                  所有者
                </label>
                <input
                  type="text"
                  id="owner_name"
                  name="owner_name"
                  value={formData.owner_name}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
              <div>
                <label htmlFor="group_name" className="block text-sm font-medium text-gray-700 mb-1">
                  グループ
                </label>
                <input
                  type="text"
                  id="group_name"
                  name="group_name"
                  value={formData.group_name}
                  onChange={handleChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                />
              </div>
            </div>

            <div className="pt-2">
              <button
                type="submit"
                disabled={saving}
                className="flex items-center justify-center px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {saving ? (
                  <>
                    <div className="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full mr-2" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    保存
                  </>
                )}
              </button>
            </div>
          </form>
        </div>

        {/* 共済情報 */}
        <div className="bg-white rounded-lg shadow p-6 mt-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-gray-900">
              共済情報
              <span className="ml-2 text-sm font-normal text-gray-400">
                ({kyosaiFields.length}件 / 計{kyosaiTotalArea.toLocaleString()}m2)
              </span>
            </h2>
            <button
              onClick={openKyosaiModal}
              className="flex items-center text-sm text-green-600 hover:text-green-700"
            >
              <Plus className="h-4 w-4 mr-1" />
              追加
            </button>
          </div>
          {kyosaiFields.length === 0 ? (
            <p className="text-gray-500 text-sm">紐づけられた共済区画はありません</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200">
                    <th className="text-left py-2 px-3 font-medium text-gray-600">耕地-分筆</th>
                    <th className="text-left py-2 px-3 font-medium text-gray-600">漢字地名</th>
                    <th className="text-left py-2 px-3 font-medium text-gray-600">住所</th>
                    <th className="text-right py-2 px-3 font-medium text-gray-600">面積(m2)</th>
                    <th className="w-10"></th>
                  </tr>
                </thead>
                <tbody>
                  {kyosaiFields.map((k) => (
                    <tr key={k.id} className="border-b border-gray-100">
                      <td className="py-2 px-3">{k.k_num}{k.s_num ? `-${k.s_num}` : ''}</td>
                      <td className="py-2 px-3">{k.kanji_name}</td>
                      <td className="py-2 px-3">{k.address}</td>
                      <td className="py-2 px-3 text-right">{k.area.toLocaleString()}</td>
                      <td className="py-2 px-1">
                        <button
                          onClick={() => removeKyosaiLink(k.id)}
                          className="text-red-400 hover:text-red-600 p-1"
                          title="紐づけ解除"
                        >
                          <X className="h-4 w-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* 中山間情報 */}
        <div className="bg-white rounded-lg shadow p-6 mt-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-gray-900">
              中山間情報
              <span className="ml-2 text-sm font-normal text-gray-400">
                ({chusankanFields.length}件 / 計{chusankanTotalArea.toLocaleString()}m2)
              </span>
            </h2>
            <button
              onClick={openChusankanModal}
              className="flex items-center text-sm text-green-600 hover:text-green-700"
            >
              <Plus className="h-4 w-4 mr-1" />
              追加
            </button>
          </div>
          {chusankanFields.length === 0 ? (
            <p className="text-gray-500 text-sm">紐づけられた中山間区画はありません</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200">
                    <th className="text-left py-2 px-3 font-medium text-gray-600">ID</th>
                    <th className="text-left py-2 px-3 font-medium text-gray-600">所在地</th>
                    <th className="text-right py-2 px-3 font-medium text-gray-600">面積(m2)</th>
                    <th className="text-right py-2 px-3 font-medium text-gray-600">支払金額</th>
                    <th className="w-10"></th>
                  </tr>
                </thead>
                <tbody>
                  {chusankanFields.map((c) => (
                    <tr key={c.id} className="border-b border-gray-100">
                      <td className="py-2 px-3">{c.c_id}</td>
                      <td className="py-2 px-3">{c.oaza} {c.aza} {c.chiban}</td>
                      <td className="py-2 px-3 text-right">{c.area.toLocaleString()}</td>
                      <td className="py-2 px-3 text-right">{c.payment_amount != null ? `¥${c.payment_amount.toLocaleString()}` : '-'}</td>
                      <td className="py-2 px-1">
                        <button
                          onClick={() => removeChusankanLink(c.id)}
                          className="text-red-400 hover:text-red-600 p-1"
                          title="紐づけ解除"
                        >
                          <X className="h-4 w-4" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* Kyosai Link Modal */}
      {showKyosaiModal && (
        <LinkModal
          title="共済区画を追加"
          items={allKyosai}
          alreadyLinkedIds={kyosaiLinkedIds}
          renderItem={(k) => (
            <div>
              <span className="font-medium">{k.k_num}{k.s_num ? `-${k.s_num}` : ''}</span>
              {' '}{k.kanji_name}
              <span className="text-gray-400 ml-2">{k.area.toLocaleString()}m2</span>
              {k.linked_field_names && k.linked_field_names.length > 0 && (
                <span className="text-gray-400 ml-2 text-xs">
                  ({k.linked_field_names.join(', ')})
                </span>
              )}
            </div>
          )}
          searchFilter={(k, q) =>
            k.kanji_name.toLowerCase().includes(q) ||
            k.address.toLowerCase().includes(q) ||
            k.k_num.includes(q)
          }
          onAdd={addKyosaiLinks}
          onClose={() => setShowKyosaiModal(false)}
        />
      )}

      {/* Chusankan Link Modal */}
      {showChusankanModal && (
        <LinkModal
          title="中山間区画を追加"
          items={allChusankan}
          alreadyLinkedIds={chusankanLinkedIds}
          renderItem={(c) => (
            <div>
              <span className="font-medium">ID{c.c_id}</span>
              {' '}{c.oaza} {c.aza} {c.chiban}
              <span className="text-gray-400 ml-2">{c.area.toLocaleString()}m2</span>
              {c.linked_field_names && c.linked_field_names.length > 0 && (
                <span className="text-gray-400 ml-2 text-xs">
                  ({c.linked_field_names.join(', ')})
                </span>
              )}
            </div>
          )}
          searchFilter={(c, q) =>
            c.c_id.includes(q) ||
            c.oaza.toLowerCase().includes(q) ||
            c.aza.toLowerCase().includes(q) ||
            c.chiban.includes(q)
          }
          onAdd={addChusankanLinks}
          onClose={() => setShowChusankanModal(false)}
        />
      )}
    </div>
  );
}
