'use client';

import { Fragment } from 'react';
import { Clock3, Download, Pencil, Trash2, Upload } from 'lucide-react';

import { StockSummary, StockTransaction } from '@/types';

interface StockOverviewProps {
  loading: boolean;
  items: StockSummary[];
  expandedMaterialId: number | null;
  historyLoadingId: number | null;
  histories: Record<number, StockTransaction[]>;
  onOpenTransaction: (
    materialId: number,
    transactionType: StockTransaction['transaction_type']
  ) => void;
  onEditTransaction: (transaction: StockTransaction) => void;
  onDeleteTransaction: (transaction: StockTransaction) => void;
  onToggleHistory: (materialId: number) => void;
}

export default function StockOverview({
  loading,
  items,
  expandedMaterialId,
  historyLoadingId,
  histories,
  onOpenTransaction,
  onEditTransaction,
  onDeleteTransaction,
  onToggleHistory,
}: StockOverviewProps) {
  if (loading) {
    return <p className="text-sm text-gray-500">読み込み中...</p>;
  }

  if (items.length === 0) {
    return (
      <div className="rounded-2xl border border-dashed border-gray-300 bg-white px-6 py-12 text-center text-gray-500">
        表示できる在庫データがありません。
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
      <table className="w-full text-sm">
        <thead className="bg-gray-50">
          <tr className="border-b border-gray-200">
            <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-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>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-100">
          {items.map((item) => {
            const isExpanded = expandedMaterialId === item.material_id;
            const history = histories[item.material_id] ?? [];

            return (
              <Fragment key={item.material_id}>
                <tr className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-medium text-gray-900">
                    <div className="flex items-center gap-2">
                      <span>{item.name}</span>
                      {!item.is_active && (
                        <span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-500">
                          無効
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{item.material_type_display}</td>
                  <td className="px-4 py-3 text-gray-600">{item.maker || '-'}</td>
                  <td className="px-4 py-3 text-right">
                    <div className="font-semibold text-gray-900">
                      在庫 {item.current_stock}
                      {item.reserved_stock !== '0.000' && (
                        <span className="ml-1 text-xs font-normal text-amber-600">
                          （引当 {item.reserved_stock}）
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-gray-500">
                      利用可能 {item.available_stock}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{item.stock_unit_display}</td>
                  <td className="px-4 py-3 text-gray-600">
                    {item.last_transaction_date ?? '-'}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-2">
                      <button
                        onClick={() => onOpenTransaction(item.material_id, 'purchase')}
                        className="inline-flex items-center gap-1 rounded-lg border border-emerald-300 px-2.5 py-1.5 text-xs text-emerald-700 transition hover:bg-emerald-50"
                      >
                        <Download className="h-3.5 w-3.5" />
                        入庫
                      </button>
                      <button
                        onClick={() => onOpenTransaction(item.material_id, 'use')}
                        className="inline-flex items-center gap-1 rounded-lg border border-amber-300 px-2.5 py-1.5 text-xs text-amber-700 transition hover:bg-amber-50"
                      >
                        <Upload className="h-3.5 w-3.5" />
                        出庫
                      </button>
                      <button
                        onClick={() => onToggleHistory(item.material_id)}
                        className="inline-flex items-center gap-1 rounded-lg border border-gray-300 px-2.5 py-1.5 text-xs text-gray-700 transition hover:bg-gray-100"
                      >
                        <Clock3 className="h-3.5 w-3.5" />
                        履歴
                      </button>
                    </div>
                  </td>
                </tr>
                {isExpanded && (
                  <tr className="bg-gray-50/70">
                    <td colSpan={7} className="px-4 py-4">
                      <div className="rounded-xl border border-gray-200 bg-white p-4">
                        <div className="mb-3 flex items-center justify-between">
                          <h3 className="text-sm font-semibold text-gray-800">
                            {item.name} の入出庫履歴
                          </h3>
                          {historyLoadingId === item.material_id && (
                            <span className="text-xs text-gray-500">読み込み中...</span>
                          )}
                        </div>
                        {history.length === 0 ? (
                          <p className="text-sm text-gray-500">履歴はまだありません。</p>
                        ) : (
                          <div className="space-y-2">
                            {history.map((transaction) => (
                              <div
                                key={transaction.id}
                                className="flex flex-col gap-1 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-700 sm:flex-row sm:items-center sm:justify-between"
                              >
                                <div className="flex items-center gap-3">
                                  <span className="font-medium text-gray-900">
                                    {transaction.transaction_type_display}
                                  </span>
                                  <span>
                                    {transaction.quantity} {transaction.stock_unit_display}
                                  </span>
                                  <span className="text-gray-500">{transaction.occurred_on}</span>
                                </div>
                                <span className="text-gray-500">
                                  {transaction.note || '備考なし'}
                                </span>
                                <div className="flex items-center gap-2">
                                  <button
                                    onClick={() => onEditTransaction(transaction)}
                                    disabled={transaction.is_locked}
                                    className="inline-flex items-center gap-1 rounded border border-blue-300 px-2 py-1 text-xs text-blue-700 hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-40"
                                  >
                                    <Pencil className="h-3 w-3" />
                                    編集
                                  </button>
                                  <button
                                    onClick={() => onDeleteTransaction(transaction)}
                                    disabled={transaction.is_locked}
                                    className="inline-flex items-center gap-1 rounded border border-red-300 px-2 py-1 text-xs text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-40"
                                  >
                                    <Trash2 className="h-3 w-3" />
                                    削除
                                  </button>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                )}
              </Fragment>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
