'use client';

import { useEffect, useState } from 'react';
import { Package, Plus, Settings2 } from 'lucide-react';
import { useRouter } from 'next/navigation';

import StockOverview from './_components/StockOverview';
import StockTransactionForm from './_components/StockTransactionForm';
import Navbar from '@/components/Navbar';
import { api } from '@/lib/api';
import { Material, StockSummary, StockTransaction } from '@/types';

type FilterTab = 'all' | 'fertilizer' | 'pesticide' | 'seed' | 'misc';

const tabs: { key: FilterTab; label: string }[] = [
  { key: 'all', label: '全て' },
  { key: 'fertilizer', label: '肥料' },
  { key: 'pesticide', label: '農薬' },
  { key: 'seed', label: '種子' },
  { key: 'misc', label: 'その他' },
];

export default function MaterialsPage() {
  const router = useRouter();
  const [tab, setTab] = useState<FilterTab>('all');
  const [loading, setLoading] = useState(true);
  const [materials, setMaterials] = useState<Material[]>([]);
  const [summaries, setSummaries] = useState<StockSummary[]>([]);
  const [histories, setHistories] = useState<Record<number, StockTransaction[]>>({});
  const [expandedMaterialId, setExpandedMaterialId] = useState<number | null>(null);
  const [historyLoadingId, setHistoryLoadingId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isTransactionOpen, setIsTransactionOpen] = useState(false);
  const [presetMaterialId, setPresetMaterialId] = useState<number | null>(null);
  const [presetTransactionType, setPresetTransactionType] =
    useState<StockTransaction['transaction_type'] | null>(null);
  const [editingTransaction, setEditingTransaction] = useState<StockTransaction | null>(null);

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

  const fetchInitialData = async () => {
    setLoading(true);
    setError(null);
    try {
      const [materialsRes, summariesRes] = await Promise.all([
        api.get('/materials/materials/'),
        api.get('/materials/stock-summary/'),
      ]);
      setMaterials(materialsRes.data);
      setSummaries(summariesRes.data);
    } catch (e) {
      console.error(e);
      setError('在庫データの取得に失敗しました。');
    } finally {
      setLoading(false);
    }
  };

  const fetchSummaryOnly = async () => {
    try {
      const res = await api.get('/materials/stock-summary/');
      setSummaries(res.data);
    } catch (e) {
      console.error(e);
      setError('在庫一覧の更新に失敗しました。');
    }
  };

  const handleToggleHistory = async (materialId: number) => {
    if (expandedMaterialId === materialId) {
      setExpandedMaterialId(null);
      return;
    }

    setExpandedMaterialId(materialId);
    if (histories[materialId]) {
      return;
    }

    setHistoryLoadingId(materialId);
    try {
      const res = await api.get(`/materials/stock-transactions/?material_id=${materialId}`);
      setHistories((prev) => ({ ...prev, [materialId]: res.data }));
    } catch (e) {
      console.error(e);
      setError('履歴の取得に失敗しました。');
    } finally {
      setHistoryLoadingId(null);
    }
  };

  const handleOpenTransaction = (
    materialId: number | null,
    transactionType: StockTransaction['transaction_type'] | null
  ) => {
    setEditingTransaction(null);
    setPresetMaterialId(materialId);
    setPresetTransactionType(transactionType);
    setIsTransactionOpen(true);
  };

  const handleEditTransaction = (transaction: StockTransaction) => {
    setPresetMaterialId(null);
    setPresetTransactionType(null);
    setEditingTransaction(transaction);
    setIsTransactionOpen(true);
  };

  const handleDeleteTransaction = async (transaction: StockTransaction) => {
    if (!confirm(`この入出庫履歴を削除しますか？\n${transaction.transaction_type_display} ${transaction.quantity}${transaction.stock_unit_display}`)) {
      return;
    }
    try {
      await api.delete(`/materials/stock-transactions/${transaction.id}/`);
      await handleSavedTransaction();
    } catch (e: unknown) {
      console.error(e);
      const detail =
        typeof e === 'object' &&
        e !== null &&
        'response' in e &&
        typeof e.response === 'object' &&
        e.response !== null &&
        'data' in e.response
          ? JSON.stringify(e.response.data)
          : '入出庫履歴の削除に失敗しました。';
      setError(detail);
    }
  };

  const handleSavedTransaction = async () => {
    await fetchSummaryOnly();

    if (expandedMaterialId !== null) {
      try {
        const res = await api.get(
          `/materials/stock-transactions/?material_id=${expandedMaterialId}`
        );
        setHistories((prev) => ({ ...prev, [expandedMaterialId]: res.data }));
      } catch (e) {
        console.error(e);
      }
    }
  };

  const filteredSummaries = summaries.filter((summary) => {
    if (tab === 'all') {
      return true;
    }
    if (tab === 'misc') {
      return summary.material_type === 'other' || summary.material_type === 'seedling';
    }
    return summary.material_type === tab;
  });

  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 flex-col gap-4 rounded-3xl bg-gradient-to-r from-emerald-600 via-green-600 to-lime-500 px-6 py-7 text-white shadow-lg sm:flex-row sm:items-end sm:justify-between">
          <div>
            <div className="mb-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-sm">
              <Package className="h-4 w-4" />
              Materials Inventory
            </div>
            <h1 className="text-2xl font-semibold">在庫管理</h1>
            <p className="mt-2 text-sm text-emerald-50">
              資材ごとの現在庫と入出庫履歴をまとめて確認できます。
            </p>
          </div>
          <div className="flex flex-wrap gap-3">
            <button
              onClick={() => router.push('/materials/masters')}
              className="inline-flex items-center gap-2 rounded-xl border border-white/30 bg-white/10 px-4 py-2 text-sm font-medium text-white transition hover:bg-white/20"
            >
              <Settings2 className="h-4 w-4" />
              資材マスタ
            </button>
            <button
              onClick={() => handleOpenTransaction(null, null)}
              className="inline-flex items-center gap-2 rounded-xl bg-white px-4 py-2 text-sm font-medium text-green-700 transition hover:bg-green-50"
            >
              <Plus className="h-4 w-4" />
              入出庫登録
            </button>
          </div>
        </div>

        {error && (
          <div className="mb-4 flex items-start gap-2 rounded-xl border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-700">
            <span>{error}</span>
            <button
              onClick={() => setError(null)}
              className="ml-auto text-red-400 transition hover:text-red-600"
            >
              ×
            </button>
          </div>
        )}

        <div className="mb-5 flex flex-wrap gap-2">
          {tabs.map((item) => (
            <button
              key={item.key}
              onClick={() => setTab(item.key)}
              className={`rounded-full px-4 py-2 text-sm font-medium transition ${
                tab === item.key
                  ? 'bg-green-600 text-white shadow-sm'
                  : 'bg-white text-gray-600 hover:bg-gray-100'
              }`}
            >
              {item.label}
            </button>
          ))}
        </div>

        <StockOverview
          loading={loading}
          items={filteredSummaries}
          expandedMaterialId={expandedMaterialId}
          historyLoadingId={historyLoadingId}
          histories={histories}
          onOpenTransaction={handleOpenTransaction}
          onEditTransaction={handleEditTransaction}
          onDeleteTransaction={handleDeleteTransaction}
          onToggleHistory={handleToggleHistory}
        />
      </div>

      <StockTransactionForm
        isOpen={isTransactionOpen}
        materials={materials}
        presetMaterialId={presetMaterialId}
        presetTransactionType={presetTransactionType}
        editingTransaction={editingTransaction}
        onClose={() => {
          setIsTransactionOpen(false);
          setEditingTransaction(null);
        }}
        onSaved={handleSavedTransaction}
      />
    </div>
  );
}
