import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { AlertTriangle, CheckCircle2, Eye, PackageSearch, Pencil, Search } from 'lucide-react';
import DateRangePicker from '../components/DateRangePicker';
import PaginationControls from '../components/PaginationControls';
import ProductTypeBadge from '../components/ProductTypeBadge';
import RefreshStatus from '../components/RefreshStatus';
import SkuPlanningModal from '../components/SkuPlanningModal';
import { classifyCutFamily, CUT_FAMILY_RULES, type CutFamilyKey } from '../analytics/cutting';
import { fetchCuttingSettings, fetchProductAnalytics, saveCuttingSettings } from '../dataService';
import { getProductTypeConfig, resolveProductType, type ProductTypeKey } from '../productClassification';
import { parseProductName } from '../productParsing';
import type { CutProductOverride, CuttingSettings, DateRange, ProductAnalyticsItem } from '../types';

type IssueKey = 'review_type' | 'missing_cut_family' | 'missing_color' | 'missing_size' | 'missing_yield';
type IssueFilter = 'all' | IssueKey;

type PlanningIssueRow = ProductAnalyticsItem & {
  productType: ProductTypeKey;
  color: string;
  size: string;
  familyKey: CutFamilyKey | '';
  familyLabel: string;
  issues: IssueKey[];
  priorityScore: number;
  hasOverride: boolean;
};

const issueLabels: Record<IssueKey, string> = {
  review_type: 'Tipo',
  missing_cut_family: 'Família',
  missing_color: 'Cor',
  missing_size: 'Tamanho',
  missing_yield: 'Rendimento'
};

const issueHelp: Record<IssueKey, string> = {
  review_type: 'O classificador não conseguiu identificar o tipo do SKU.',
  missing_cut_family: 'SKU de vestuário não caiu em uma família de corte confiável.',
  missing_color: 'SKU de vestuário não tem cor clara para planejamento.',
  missing_size: 'SKU de vestuário não tem tamanho claro para planejamento.',
  missing_yield: 'A família existe, mas ainda falta rendimento em unidades por rolo.'
};

const issueFilters: Array<{ value: IssueFilter; label: string }> = [
  { value: 'all', label: 'Todos' },
  { value: 'review_type', label: issueLabels.review_type },
  { value: 'missing_cut_family', label: issueLabels.missing_cut_family },
  { value: 'missing_color', label: issueLabels.missing_color },
  { value: 'missing_size', label: issueLabels.missing_size },
  { value: 'missing_yield', label: issueLabels.missing_yield }
];

const familyLabels = new Map<CutFamilyKey, string>([
  ...CUT_FAMILY_RULES.map(rule => [rule.key, `${rule.materialLabel} · ${rule.label}`] as const),
  ['OUTROS', 'Sem regra']
]);

const formatNumber = (value: number, maximumFractionDigits = 0) => (
  new Intl.NumberFormat('pt-BR', { maximumFractionDigits }).format(value)
);

const formatCurrency = (value: number) => (
  new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value)
);

const buildIssues = (
  product: ProductAnalyticsItem,
  settings: CuttingSettings
): PlanningIssueRow => {
  const override = settings.productOverrides[product.id];
  const metadata = parseProductName(product.name);
  const productType = resolveProductType(product.name, override);
  const familyKey = override?.familyKey || classifyCutFamily(metadata.baseName).key;
  const color = override?.color || metadata.color;
  const size = (override?.size || metadata.size).toUpperCase();
  const issues: IssueKey[] = [];

  if (productType === 'unknown') issues.push('review_type');

  if (productType === 'finished_apparel') {
    if (familyKey === 'OUTROS') issues.push('missing_cut_family');
    if (!color) issues.push('missing_color');
    if (!size) issues.push('missing_size');
    if (familyKey !== 'OUTROS' && !settings.familyYields[familyKey]) issues.push('missing_yield');
  }

  return {
    ...product,
    productType,
    color,
    size,
    familyKey,
    familyLabel: familyLabels.get(familyKey) || '-',
    issues,
    priorityScore: (product.quantitySold * 2) + (product.revenue / 100),
    hasOverride: Boolean(override)
  };
};

const PlanningIssuesSkeleton = () => (
  <div className="overflow-hidden rounded-2xl border border-dark-border bg-dark-card shadow-sm" aria-label="Carregando dados pendentes">
    <div className="border-b border-dark-border p-4">
      <div className="grid grid-cols-[120px_1.4fr_150px_170px_130px_130px_120px] gap-5">
        {[0, 1, 2, 3, 4, 5, 6].map(item => <div key={item} className="skeleton h-3" />)}
      </div>
    </div>
    <div className="divide-y divide-dark-border">
      {[0, 1, 2, 3, 4, 5].map(row => (
        <div key={row} className="grid grid-cols-[120px_1.4fr_150px_170px_130px_130px_120px] gap-5 px-6 py-4">
          {[0, 1, 2, 3, 4, 5, 6].map(item => <div key={item} className="skeleton h-4" />)}
        </div>
      ))}
    </div>
  </div>
);

const PlanningIssues = () => {
  const { dateRange, setDateRange } = useOutletContext<{
    dateRange: DateRange,
    setDateRange: (range: DateRange) => void
  }>();
  const [products, setProducts] = useState<ProductAnalyticsItem[]>([]);
  const [settings, setSettings] = useState<CuttingSettings>({ familyYields: {}, productOverrides: {} });
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [issueFilter, setIssueFilter] = useState<IssueFilter>('all');
  const [editingProduct, setEditingProduct] = useState<PlanningIssueRow | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(20);

  useEffect(() => {
    let isMounted = true;

    const loadData = async () => {
      setIsLoading(true);
      const [productData, planningSettings] = await Promise.all([
        fetchProductAnalytics(dateRange),
        fetchCuttingSettings()
      ]);

      if (isMounted) {
        setProducts(productData);
        setSettings(planningSettings);
        setIsLoading(false);
      }
    };

    void loadData();

    return () => {
      isMounted = false;
    };
  }, [dateRange]);

  const rows = useMemo(() => {
    const normalizedSearch = searchTerm.trim().toLowerCase();

    return products
      .map(product => buildIssues(product, settings))
      .filter(row => row.issues.length > 0)
      .filter(row => issueFilter === 'all' || row.issues.includes(issueFilter))
      .filter(row => {
        if (!normalizedSearch) return true;
        const typeLabel = getProductTypeConfig(row.productType).label.toLowerCase();
        return (
          row.id.toLowerCase().includes(normalizedSearch) ||
          row.name.toLowerCase().includes(normalizedSearch) ||
          row.color.toLowerCase().includes(normalizedSearch) ||
          row.size.toLowerCase().includes(normalizedSearch) ||
          row.familyLabel.toLowerCase().includes(normalizedSearch) ||
          typeLabel.includes(normalizedSearch)
        );
      })
      .sort((a, b) => {
        if (b.issues.length !== a.issues.length) return b.issues.length - a.issues.length;
        return b.priorityScore - a.priorityScore;
      });
  }, [issueFilter, products, searchTerm, settings]);

  const issueCounts = useMemo(() => {
    const counts = new Map<IssueKey, number>();
    products
      .map(product => buildIssues(product, settings))
      .forEach(row => row.issues.forEach(issue => counts.set(issue, (counts.get(issue) || 0) + 1)));
    return counts;
  }, [products, settings]);

  const saveProductOverride = async (productId: string, override: CutProductOverride | null) => {
    const productOverrides = { ...settings.productOverrides };
    if (override) {
      productOverrides[productId] = override;
    } else {
      delete productOverrides[productId];
    }

    const nextSettings = { ...settings, productOverrides };
    setIsSaving(true);
    try {
      const savedSettings = await saveCuttingSettings(nextSettings);
      setSettings(savedSettings);
      setEditingProduct(null);
    } finally {
      setIsSaving(false);
    }
  };

  const totalPages = Math.ceil(rows.length / itemsPerPage);
  const safeCurrentPage = Math.min(currentPage, totalPages || 1);
  const startIndex = (safeCurrentPage - 1) * itemsPerPage;
  const paginatedRows = rows.slice(startIndex, startIndex + itemsPerPage);
  const isRefreshing = isLoading && products.length > 0;

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 gap-4 2xl:grid-cols-[minmax(520px,1fr)_auto] 2xl:items-start">
        <div>
          <h1 className="mb-2 text-2xl font-bold text-zinc-900 dark:text-dark-text">Dados Pendentes</h1>
          <p className="font-medium text-zinc-500 dark:text-dark-muted">
            Fila principal para revisar tipo, cor, tamanho, família e rendimento dos SKUs.
          </p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center 2xl:justify-end">
          <Link
            to="/registrations"
            className="inline-flex h-10 items-center justify-center gap-2 rounded-xl border border-dark-border bg-dark-card px-4 text-sm font-bold text-dark-text transition-colors hover:border-brand-primary"
          >
            <PackageSearch className="h-4 w-4 text-brand-primary" />
            Cadastros
          </Link>
          <DateRangePicker
            dateRange={dateRange}
            onChange={(range) => {
              setDateRange(range);
              setCurrentPage(1);
            }}
          />
        </div>
      </div>

      <RefreshStatus isRefreshing={isRefreshing} />

      <div className="grid grid-cols-1 gap-4 md:grid-cols-3 xl:grid-cols-5">
        {issueFilters.filter(option => option.value !== 'all').map(option => {
          const count = issueCounts.get(option.value as IssueKey) || 0;
          return (
            <button
              key={option.value}
              type="button"
              onClick={() => {
                setIssueFilter(option.value);
                setCurrentPage(1);
              }}
              className={`rounded-2xl border p-4 text-left transition-colors cursor-pointer ${
                issueFilter === option.value
                  ? 'border-brand-primary/45 bg-brand-primary/10'
                  : 'border-dark-border bg-dark-card hover:border-brand-primary/35'
              }`}
              title={issueHelp[option.value as IssueKey]}
            >
              <div className="flex items-center justify-between gap-3">
                <span className="text-xs font-bold uppercase tracking-widest text-dark-muted">{option.label}</span>
                <AlertTriangle className={count ? 'h-4 w-4 text-amber-300' : 'h-4 w-4 text-emerald-300'} />
              </div>
              <div className="mt-3 text-2xl font-bold text-dark-text">{formatNumber(count)}</div>
            </button>
          );
        })}
      </div>

      <div className="grid grid-cols-1 gap-3 rounded-2xl border border-dark-border bg-dark-card p-4 shadow-sm xl:grid-cols-[minmax(360px,1fr)_auto] xl:items-center">
          <div className="flex flex-col gap-3 md:flex-row md:items-center">
            <div className="relative w-full md:w-96">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-dark-muted" />
              <input
                type="text"
                value={searchTerm}
                onChange={(event) => {
                  setSearchTerm(event.target.value);
                  setCurrentPage(1);
                }}
                placeholder="Buscar SKU, produto, cor, tipo..."
                className="h-10 w-full rounded-xl border border-dark-border bg-dark-input pl-10 pr-3 text-sm font-semibold text-dark-text outline-none transition-colors placeholder:text-dark-muted focus:border-brand-primary"
              />
            </div>
            <select
              value={issueFilter}
              onChange={(event) => {
                setIssueFilter(event.target.value as IssueFilter);
                setCurrentPage(1);
              }}
              className="h-10 rounded-xl border border-dark-border bg-dark-input px-3 text-sm font-bold text-dark-text outline-none transition-colors focus:border-brand-primary cursor-pointer"
            >
              {issueFilters.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>
          <div className="text-sm font-semibold text-dark-muted">
            {formatNumber(rows.length)} SKUs pendentes
          </div>
      </div>

        {isLoading && !products.length ? (
          <PlanningIssuesSkeleton />
        ) : rows.length ? (
          <div className="overflow-hidden rounded-2xl border border-dark-border bg-dark-card shadow-sm">
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1180px] table-fixed text-left text-sm">
                <colgroup>
                  <col className="w-[120px]" />
                  <col className="w-[380px]" />
                  <col className="w-[150px]" />
                  <col className="w-[180px]" />
                  <col className="w-[140px]" />
                  <col className="w-[140px]" />
                  <col className="w-[120px]" />
                  <col className="w-[120px]" />
                </colgroup>
                <thead className="border-b border-dark-border bg-dark-header text-dark-muted">
                  <tr>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">SKU</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Produto</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Tipo</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Pendências</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Família</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Vendido</th>
                    <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-wider">Receita</th>
                    <th className="px-4 py-4 text-right text-[10px] font-bold uppercase tracking-wider">Ações</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-dark-border">
                  {paginatedRows.map(row => (
                    <tr key={row.id} className="transition-colors hover:bg-dark-input/50">
                      <td className="px-6 py-2.5 font-mono text-[11px] text-dark-muted">#{row.id}</td>
                      <td className="max-w-0 px-6 py-2.5">
                        <div className="truncate font-semibold text-dark-text" title={row.name}>{row.name}</div>
                        <div className="mt-1 flex min-w-0 items-center gap-2 text-[10px] font-semibold text-dark-muted">
                          <span className="truncate">Cor: {row.color || '-'}</span>
                          <span>·</span>
                          <span className="truncate">Tam.: {row.size || '-'}</span>
                          {row.hasOverride && <span className="rounded-full border border-brand-primary/25 bg-brand-primary/10 px-2 py-0.5 text-brand-primary">manual</span>}
                        </div>
                      </td>
                      <td className="px-6 py-2.5">
                        <ProductTypeBadge type={row.productType} />
                      </td>
                      <td className="px-6 py-2.5">
                        <div className="flex flex-wrap gap-1.5">
                          {row.issues.map(issue => (
                            <span
                              key={issue}
                              className="inline-flex rounded-full border border-amber-400/25 bg-amber-400/10 px-2 py-0.5 text-[10px] font-bold text-amber-300"
                              title={issueHelp[issue]}
                            >
                              {issueLabels[issue]}
                            </span>
                          ))}
                        </div>
                      </td>
                      <td className="px-6 py-2.5 text-xs font-bold text-dark-text">{row.familyLabel}</td>
                      <td className="px-6 py-2.5 whitespace-nowrap font-bold text-dark-text">{formatNumber(row.quantitySold)} un.</td>
                      <td className="px-6 py-2.5 whitespace-nowrap font-bold text-brand-primary">{formatCurrency(row.revenue)}</td>
                      <td className="px-4 py-2.5 text-right">
                        <div className="flex justify-end gap-2">
                          <button
                            type="button"
                            onClick={() => setEditingProduct(row)}
                            className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-dark-input text-dark-text transition-colors hover:bg-dark-border cursor-pointer"
                            title={`Editar planejamento do SKU ${row.id}`}
                            aria-label={`Editar planejamento do SKU ${row.id}`}
                          >
                            <Pencil className="h-3.5 w-3.5" />
                          </button>
                          <Link
                            to={`/products/${row.id}`}
                            className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-brand-primary/10 text-brand-primary transition-opacity hover:opacity-80 cursor-pointer"
                            title={`Ver SKU ${row.id}`}
                            aria-label={`Ver SKU ${row.id}`}
                          >
                            <Eye className="h-3.5 w-3.5" />
                          </Link>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <PaginationControls
              totalItems={rows.length}
              currentPage={safeCurrentPage}
              totalPages={totalPages}
              pageSize={itemsPerPage}
              pageSizeOptions={[10, 20, 50, 100]}
              itemLabel="SKUs"
              pageSizeLabel="por página"
              startIndex={startIndex}
              endIndex={Math.min(startIndex + itemsPerPage, rows.length)}
              onPageChange={setCurrentPage}
              onPageSizeChange={(size) => {
                setItemsPerPage(size);
                setCurrentPage(1);
              }}
            />
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center rounded-2xl border border-dark-border bg-dark-card px-6 py-16 text-center shadow-sm">
            {products.length ? (
              <>
                <CheckCircle2 className="h-10 w-10 text-emerald-300" />
                <p className="mt-4 text-sm font-bold text-dark-text">Nenhum dado pendente neste filtro.</p>
                <p className="mt-1 text-sm font-semibold text-dark-muted">Ajuste o filtro ou o período para revisar outros SKUs.</p>
              </>
            ) : (
              <>
                <PackageSearch className="h-10 w-10 text-dark-muted" />
                <p className="mt-4 text-sm font-bold text-dark-text">Sem produtos no período.</p>
                <p className="mt-1 text-sm font-semibold text-dark-muted">Altere o intervalo de datas para carregar a fila.</p>
              </>
            )}
          </div>
        )}

      {editingProduct && (
        <SkuPlanningModal
          product={editingProduct}
          override={settings.productOverrides[editingProduct.id]}
          isSaving={isSaving}
          onClose={() => setEditingProduct(null)}
          onSave={(override) => saveProductOverride(editingProduct.id, override)}
        />
      )}
    </div>
  );
};

export default PlanningIssues;
