'use client';

import { useMemo, useState, useCallback } from 'react';
import { LayoutShell } from '../../../../components/layout-shell';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import api from '../../../../lib/api-client';
import { PlanMetricsPanel } from '../../../../components/insights/plan-metrics-panel';
import { AdaptiveIngestorPanel } from '../../../../components/import/adaptive-ingestor-panel';
import { usePlanMetrics } from '../../../../hooks/use-plan-metrics';
import { smartRound } from '../../../../lib/utils';
import { DataTable, Column } from '../../../../components/ui/data-table';
import { Trash2 } from 'lucide-react';
import { ConfirmModal } from '../../../../components/ui/modal';
import { useToast } from '../../../../components/ui/toast';
import { PlanDetailsModal } from './plan-details-modal';

type PlanRow = {
  id: number;
  school_name: string;
  commodity_name: string;
  planned_quantity: number;
  remaining_quantity: number | null;
};

export default function SupplyPlansPage() {
  const queryClient = useQueryClient();
  const { showToast } = useToast();
  const [selectedPeriod, setSelectedPeriod] = useState<string>('');
  const [file, setFile] = useState<File | null>(null);
  const [ingestSummary, setIngestSummary] = useState<any | null>(null);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowsToDelete, setRowsToDelete] = useState<PlanRow[]>([]);
  const [selectedPlan, setSelectedPlan] = useState<PlanRow | null>(null);

  const { data: planPeriodsData } = useQuery({
    queryKey: ['plan-periods'],
    queryFn: async () => {
      const response = await api.get('/plan-periods');
      return response.data?.data ?? [];
    },
    staleTime: 5 * 60 * 1000,
  });

  const planPeriods = Array.isArray(planPeriodsData) ? planPeriodsData : [];
  
  // Default to the active period, or the first one if none are active
  const activePeriod = planPeriods.find((p: any) => p.is_active);
  const dataDefaultId = activePeriod?.id?.toString() || planPeriods?.[0]?.id?.toString() || '';
  
  const activePeriodId = selectedPeriod || dataDefaultId;
  const { data: metrics } = usePlanMetrics(activePeriodId);

  const { data: plans, isFetching } = useQuery({
    queryKey: ['supply-plans', activePeriodId, page, search],
    queryFn: async () => {
      if (!activePeriodId) return { data: [], meta: { last_page: 1 } };
      const response = await api.get('/supply-plans', {
        params: {
          plan_period_id: activePeriodId,
          page,
          per_page: 20,
          search
        },
      });
      // Backend returns { data: [], pagination: { total, last_page, ... } }
      // But our axios interceptor might be unwrapping it or we need to handle it.
      // Let's assume standard response structure.
      return response.data;
    },
    enabled: Boolean(activePeriodId),
    placeholderData: (previousData) => previousData, // Keep previous data while fetching
  });

  const { data: importHistory } = useQuery({
    queryKey: ['plan-imports'],
    queryFn: async () => {
      const response = await api.get('/supply-plan-imports', { params: { per_page: 10 } });
      return response.data;
    },
  });

  const uploadMutation = useMutation({
    mutationFn: async () => {
      if (!file || !activePeriodId) throw new Error('Missing period or file');
      const formData = new FormData();
      formData.append('plan_period_id', activePeriodId);
      formData.append('file', file);
      const response = await api.post('/supply-plan-imports', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 120000, // Increase timeout to 2 minutes for large files
      });
      return response.data;
    },
    onSuccess: (payload: any) => {
      setFile(null);
      setIngestSummary(payload?.summary ?? null);
      queryClient.invalidateQueries({ queryKey: ['supply-plans', activePeriodId] });
      queryClient.invalidateQueries({ queryKey: ['plan-imports'] });
      queryClient.invalidateQueries({ queryKey: ['plan-metrics', activePeriodId] });
      showToast({ title: 'Import successful', type: 'success' });
    },
    onError: (error: Error) => {
      showToast({ title: 'Import failed', message: error.message, type: 'error' });
    }
  });

  const deleteMutation = useMutation({
    mutationFn: async (ids: number[]) => {
      await api.post('/supply-plans/bulk-delete', { ids });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['supply-plans', activePeriodId] });
      setIsDeleteModalOpen(false);
      setRowsToDelete([]);
      showToast({ title: 'Records deleted', type: 'success' });
    },
    onError: () => {
      showToast({ title: 'Delete failed', type: 'error' });
    }
  });



    const columns: Column<PlanRow>[] = [
      { key: 'school_name', label: 'School', sortable: true },
      { key: 'commodity_name', label: 'Commodity', sortable: true },
      {
        key: 'planned_quantity',
        label: 'Planned',
        render: (row) => <span className="font-semibold">{smartRound(row.planned_quantity)}</span>,
      },
      {
        key: 'remaining_quantity',
        label: 'Remaining',
        render: (row) => {
          const remaining = row.remaining_quantity ?? row.planned_quantity;
          const delivered = row.planned_quantity - remaining;
          const percent = row.planned_quantity > 0 ? (remaining / row.planned_quantity) * 100 : 0;
          
          let statusColor = 'text-emerald-600 bg-emerald-50';
          let statusText = 'On Track';

          // Intelligence Logic per user request
          if (Math.abs(remaining - row.planned_quantity) < 0.01) {
             // Nothing delivered yet
             statusColor = 'text-slate-500 bg-slate-100';
             statusText = 'No Deliveries Recorded';
          } else if (percent < 20) {
            statusColor = 'text-rose-600 bg-rose-50';
            statusText = 'Critical Stock';
          } else if (percent < 50) {
            statusColor = 'text-amber-600 bg-amber-50';
            statusText = 'Low Stock';
          } else {
             statusText = 'Deliveries Active';
          }

          return (
            <div className="flex items-center gap-2">
              <span className="font-medium text-slate-900">{smartRound(remaining)}</span>
              <span className={`whitespace-nowrap rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${statusColor}`}>
                {statusText}
              </span>
            </div>
          );
        },
      },
    ];

    return (
      <LayoutShell role="SUPER_ADMIN">
        <div className="flex flex-col gap-6">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
            <div>
              <h1 className="text-2xl font-bold text-slate-900">Supply plan</h1>
              <p className="text-sm text-slate-500">Upload JSON, CSV, or Excel allocations and compare planned vs remaining balances.</p>
            </div>
            <div className="flex flex-col gap-2 text-sm text-slate-500">
              <label className="text-xs font-semibold uppercase tracking-wide text-slate-600">Plan period</label>
              <select
                value={activePeriodId}
                onChange={(event) => setSelectedPeriod(event.target.value)}
                className="rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-brand focus:outline-none"
              >
                {planPeriods.length === 0 && <option value="">No plan periods available</option>}
                {planPeriods.map((period: any) => (
                  <option key={period.id} value={period.id}>
                    {period.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <PlanMetricsPanel metrics={metrics ?? undefined} />

          <div className="grid gap-4 md:grid-cols-2">
            <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
              <p className="text-xs uppercase text-slate-500">Total planned</p>
              <p className="mt-2 text-3xl font-bold text-slate-900">{smartRound(plans?.aggregations?.total_planned ?? 0).toLocaleString()}</p>
            </div>
            <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
              <p className="text-xs uppercase text-slate-500">Total remaining</p>
              <p className="mt-2 text-3xl font-bold text-brand">{smartRound(plans?.aggregations?.total_remaining ?? 0).toLocaleString()}</p>
            </div>
          </div>

          <div className="rounded-2xl border border-dashed border-brand/30 bg-white/70 p-5 shadow-inner">
            <form
              onSubmit={(event) => {
                event.preventDefault();
                uploadMutation.mutate();
              }}
              className="flex flex-col gap-4"
            >
              <div>
                <label className="text-xs font-semibold uppercase tracking-wide text-slate-600">Upload JSON, CSV, or XLSX</label>
                <input
                  type="file"
                  accept=".json,.csv,application/json,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  onChange={(event) => setFile(event.target.files?.[0] ?? null)}
                  className="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
                <p className="mt-1 text-xs text-slate-500">
                  The ingestor maps <code>school_code</code>, <code>commodity_code</code>, and <code>planned_quantity</code> even if the
                  columns are renamed.
                </p>
              </div>
              <div className="flex items-center gap-3">
                <button
                  type="submit"
                  disabled={!file || uploadMutation.isPending || !activePeriodId}
                  className="inline-flex items-center justify-center rounded-lg bg-brand px-5 py-2 text-sm font-semibold text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {uploadMutation.isPending ? 'Uploading…' : 'Import plan file'}
                </button>
                {uploadMutation.isSuccess && (
                  <span className="text-sm text-emerald-700">Import complete.</span>
                )}
                {uploadMutation.isError && (
                  <span className="text-sm text-rose-600">Failed: {(uploadMutation.error as Error).message}</span>
                )}
              </div>
            </form>
          </div>

          <AdaptiveIngestorPanel summary={ingestSummary ?? undefined} />

          <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
            <DataTable
              columns={columns}
              data={plans?.data ?? []}
              serverSide
              pageCount={plans?.pagination?.last_page ?? 1}
              currentPage={page}
              onPageChange={setPage}
              isLoading={isFetching}
              searchable
              onSearch={useCallback((query: string) => {
                setSearch(query);
                setPage(1);
              }, [])}
              selectable
              bulkActions={[
                {
                  label: 'Delete',
                  icon: Trash2,
                  variant: 'danger',
                  onClick: (rows) => {
                    setRowsToDelete(rows);
                    setIsDeleteModalOpen(true);
                  }
                }
              ]}
              onRowClick={(row) => setSelectedPlan(row)}
            />
          </div>

          <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-slate-900">Recent imports</h2>
              <span className="text-xs uppercase text-slate-400">Latest 10</span>
            </div>
            <div className="space-y-3 text-sm">
              {(importHistory?.data ?? []).map((row: any) => (
                <div key={row.id} className="flex items-center justify-between rounded-xl border border-slate-100 px-4 py-3">
                  <div>
                    <p className="font-semibold text-slate-900">{row.original_filename}</p>
                    <p className="text-xs text-slate-500">
                      {row.plan_period_label} • {row.imported_by_name}
                    </p>
                  </div>
                  <div className="text-right">
                    <p className="text-xs uppercase tracking-wide text-slate-400">Rows</p>
                    <p className="text-base font-semibold text-brand">{row.imported_rows}</p>
                    <p className="text-xs text-slate-500">{row.status}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <PlanDetailsModal 
          isOpen={!!selectedPlan} 
          onClose={() => setSelectedPlan(null)} 
          plan={selectedPlan} 
        />

        <ConfirmModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          onConfirm={() => deleteMutation.mutate(rowsToDelete.map(r => r.id))}
          title="Delete Supply Plans"
          message={`Are you sure you want to delete ${rowsToDelete.length} records? This action cannot be undone.`}
          confirmLabel="Delete"
          variant="danger"
          isLoading={deleteMutation.isPending}
        />
      </LayoutShell>
    );
  }
