import { useEffect, useMemo, useState } from "react";
import { Calculator, DollarSign, Info, Plus, Trash2 } from "lucide-react";

import { SearchableMultiSelect } from "@/components/board/SearchableMultiSelect";
import { SearchableSelect } from "@/components/board/SearchableSelect";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import {
  defaultTariffAmount,
  formatTariffRange,
  type TariffCatalogItem,
  type TariffWorkType,
} from "@/data/tariff";
import type { ProjectPricingItemInput } from "@/lib/store";
import { useTariffCatalog } from "@/lib/tariffCatalog";
import { useTariffSections, type TariffSection } from "@/lib/tariffSections";
import { normalizeOptionKey } from "@/lib/optionUtils";
import { cn } from "@/lib/utils";

interface Props {
  client: string;
  items: ProjectPricingItemInput[];
  onChange: (items: ProjectPricingItemInput[]) => void;
  loading?: boolean;
  error?: string | null;
}

function parseAmount(value: string) {
  const parsed = Number(value.replace(/,/g, "").trim());
  return Number.isFinite(parsed) ? parsed : 0;
}

function formatCurrency(value: number) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: 2,
  }).format(value || 0);
}

function findDefaultWorkType(item?: TariffCatalogItem | null) {
  return item?.workTypes[0] || null;
}

function findDefaultLevel(workType?: TariffWorkType | null) {
  return workType?.levels[0] || null;
}

function clean(value: string) {
  return value.trim();
}

function getFixedLevel(item: TariffCatalogItem) {
  const workType = item.workTypes[0] || null;
  const level = workType?.levels[0] || null;
  return { workType, level };
}

function getFixedAmount(item: TariffCatalogItem) {
  const { level } = getFixedLevel(item);
  const amount = Number(level?.min ?? level?.max ?? 0);
  return Number.isFinite(amount) ? amount : 0;
}

function isLegacyWmcItem(item: ProjectPricingItemInput, section: TariffSection) {
  return (
    section.id === "wmc" &&
    item.source === "tariff" &&
    (normalizeOptionKey(item.workType) === normalizeOptionKey("Tarifa fija WMC") ||
      normalizeOptionKey(item.category) === normalizeOptionKey("Walmart Connect"))
  );
}

function itemBelongsToSpecialSection(item: ProjectPricingItemInput, section: TariffSection) {
  if (item.source !== "tariff") return false;
  if (item.tariffSectionId) return item.tariffSectionId === section.id;
  return isLegacyWmcItem(item, section);
}

function createSpecialPricingItem(
  catalogItem: TariffCatalogItem,
  section: TariffSection,
): ProjectPricingItemInput | null {
  const { workType, level } = getFixedLevel(catalogItem);
  const amount = getFixedAmount(catalogItem);

  if (!workType || !level || amount <= 0) return null;

  return {
    source: "tariff",
    category: section.name,
    serviceName: catalogItem.service,
    workType: `Tarifa fija · ${section.name}`,
    complexityLevel: "Precio fijo",
    referenceLabel: formatTariffRange(level),
    referenceMin: amount,
    referenceMax: amount,
    amount,
    description: catalogItem.notes || "",
    tariffSectionId: section.id,
    tariffCatalogId: catalogItem.id,
  };
}

export function ProjectPricingPanel({ client, items, onChange, loading, error }: Props) {
  const [sectionId, setSectionId] = useState<string>("grafico");
  const [serviceLabel, setServiceLabel] = useState<string>("");
  const [workTypeId, setWorkTypeId] = useState<string>("");
  const [levelId, setLevelId] = useState<string>("");
  const [amount, setAmount] = useState<string>("");
  const [description, setDescription] = useState<string>("");
  const [manualName, setManualName] = useState<string>("");
  const [manualDescription, setManualDescription] = useState<string>("");
  const [manualAmount, setManualAmount] = useState<string>("");

  const {
    catalog: tariffCatalog,
    loading: tariffLoading,
    error: tariffError,
  } = useTariffCatalog();
  const {
    sections,
    loading: sectionsLoading,
    error: sectionsError,
  } = useTariffSections();

  const generalSections = useMemo(
    () =>
      sections.filter(
        (section) => section.isActive && section.scope === "general" && section.pricingMode === "guided",
      ),
    [sections],
  );

  const specialSections = useMemo(() => {
    const clientKey = normalizeOptionKey(client);
    if (!clientKey) return [];

    return sections.filter(
      (section) =>
        section.isActive &&
        section.scope === "client" &&
        section.pricingMode === "fixed_multi" &&
        normalizeOptionKey(section.clientName) === clientKey,
    );
  }, [client, sections]);

  const hasSpecialTariff = specialSections.length > 0;
  const activeGeneralSection =
    generalSections.find((section) => section.id === sectionId) || generalSections[0] || null;

  useEffect(() => {
    if (!activeGeneralSection && generalSections.length) {
      setSectionId(generalSections[0].id);
    } else if (activeGeneralSection && activeGeneralSection.id !== sectionId) {
      setSectionId(activeGeneralSection.id);
    }
  }, [activeGeneralSection, generalSections, sectionId]);

  const serviceOptions = useMemo(
    () =>
      tariffCatalog
        .filter((item) => item.section === activeGeneralSection?.id)
        .map((item) => `${item.category} · ${item.service}`),
    [activeGeneralSection?.id, tariffCatalog],
  );

  const selectedItem = useMemo(
    () =>
      tariffCatalog.find(
        (item) =>
          item.section === activeGeneralSection?.id &&
          `${item.category} · ${item.service}` === serviceLabel,
      ) || null,
    [activeGeneralSection?.id, serviceLabel, tariffCatalog],
  );

  const selectedWorkType = useMemo(() => {
    if (!selectedItem) return null;
    return selectedItem.workTypes.find((workType) => workType.id === workTypeId) || null;
  }, [selectedItem, workTypeId]);

  const selectedLevel = useMemo(() => {
    if (!selectedWorkType) return null;
    return selectedWorkType.levels.find((level) => level.id === levelId) || null;
  }, [selectedWorkType, levelId]);

  const total = items.reduce((sum, item) => sum + Number(item.amount || 0), 0);

  const resetTariffSelection = () => {
    setServiceLabel("");
    setWorkTypeId("");
    setLevelId("");
    setAmount("");
    setDescription("");
  };

  const onSectionChange = (name: string) => {
    const section = generalSections.find((item) => item.name === name);
    setSectionId(section?.id || generalSections[0]?.id || "");
    resetTariffSelection();
  };

  const onServiceChange = (label: string) => {
    setServiceLabel(label);
    const item = tariffCatalog.find(
      (catalogItem) =>
        catalogItem.section === activeGeneralSection?.id &&
        `${catalogItem.category} · ${catalogItem.service}` === label,
    );
    const firstWorkType = findDefaultWorkType(item);
    const firstLevel = findDefaultLevel(firstWorkType);

    setWorkTypeId(firstWorkType?.id || "");
    setLevelId(firstLevel?.id || "");
    setAmount(defaultTariffAmount(firstLevel));
    setDescription("");
  };

  const onWorkTypeChange = (label: string) => {
    if (!selectedItem) return;
    const workType = selectedItem.workTypes.find((item) => item.label === label);
    const firstLevel = findDefaultLevel(workType);

    setWorkTypeId(workType?.id || "");
    setLevelId(firstLevel?.id || "");
    setAmount(defaultTariffAmount(firstLevel));
  };

  const onLevelChange = (label: string) => {
    if (!selectedWorkType) return;
    const level = selectedWorkType.levels.find((item) => item.label === label);
    setLevelId(level?.id || "");
    setAmount(defaultTariffAmount(level));
  };

  const addTariffItem = () => {
    if (!selectedItem || !selectedWorkType || !selectedLevel || !activeGeneralSection) return;

    const finalAmount = parseAmount(amount);
    if (finalAmount <= 0) return;

    onChange([
      ...items,
      {
        source: "tariff",
        category: selectedItem.category,
        serviceName: selectedItem.service,
        workType: selectedWorkType.label,
        complexityLevel: selectedLevel.label,
        referenceLabel: formatTariffRange(selectedLevel),
        referenceMin: selectedLevel.min ?? null,
        referenceMax: selectedLevel.max ?? null,
        amount: finalAmount,
        description: clean(description),
        tariffSectionId: activeGeneralSection.id,
        tariffCatalogId: selectedItem.id,
      },
    ]);

    setDescription("");
    setAmount(defaultTariffAmount(selectedLevel));
  };

  const onSpecialServicesChange = (section: TariffSection, services: string[]) => {
    const sectionCatalog = tariffCatalog.filter(
      (item) => item.section === section.id && getFixedAmount(item) > 0,
    );
    const existingItems = items.filter((item) => itemBelongsToSpecialSection(item, section));
    const existingByService = new Map(
      existingItems.map((item) => [normalizeOptionKey(item.serviceName), item] as const),
    );
    const catalogByService = new Map(
      sectionCatalog.map((item) => [normalizeOptionKey(item.service), item] as const),
    );

    const nextSectionItems = services
      .map((service) => {
        const key = normalizeOptionKey(service);
        return (
          existingByService.get(key) ||
          (catalogByService.get(key)
            ? createSpecialPricingItem(catalogByService.get(key)!, section)
            : null)
        );
      })
      .filter((item): item is ProjectPricingItemInput => Boolean(item));

    const otherItems = items.filter((item) => !itemBelongsToSpecialSection(item, section));
    onChange([...otherItems, ...nextSectionItems]);
  };

  const manualContext = specialSections[0] || null;
  const allowManual = !hasSpecialTariff || specialSections.some((section) => section.allowManual);

  const addManualItem = () => {
    const finalAmount = parseAmount(manualAmount);
    const contextName = manualContext?.name || "Otros";
    const name =
      clean(manualName) ||
      (manualContext ? `Propuesta general ${manualContext.clientName}` : "Otros / costo manual");

    if (finalAmount <= 0) return;

    onChange([
      ...items,
      {
        source: "manual",
        category: contextName,
        serviceName: name,
        workType: "Manual",
        complexityLevel: "",
        referenceLabel: "Monto manual",
        referenceMin: null,
        referenceMax: null,
        amount: finalAmount,
        description: clean(manualDescription),
        tariffSectionId: manualContext?.id,
      },
    ]);

    setManualName("");
    setManualDescription("");
    setManualAmount("");
  };

  const removeItem = (index: number) => {
    onChange(items.filter((_, itemIndex) => itemIndex !== index));
  };

  const selectedWorkTypeLabel = selectedWorkType?.label || "";
  const selectedLevelLabel = selectedLevel?.label || "";
  const combinedError = error || tariffError || sectionsError;

  return (
    <div className="md:col-span-2 rounded-2xl border border-border bg-muted/20 p-4">
      <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex items-start gap-2.5">
          <span className="mt-0.5 flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-primary">
            <Calculator className="h-4 w-4" />
          </span>
          <div>
            <h3 className="text-sm font-semibold">Tarifario / Estimación interna</h3>
            <p className="text-xs text-muted-foreground">
              {hasSpecialTariff
                ? `Este cliente tiene ${specialSections.length === 1 ? "un tarifario especial" : "tarifarios especiales"}. Selecciona piezas o agrega un costo manual.`
                : "Agrega costos del tarifario general o montos manuales. El total se guarda automáticamente como monto interno del proyecto."}
            </p>
          </div>
        </div>

        <div className="flex w-full flex-shrink-0 items-center justify-between gap-3 rounded-xl border border-primary/20 bg-card px-3 py-2 shadow-sm sm:w-auto">
          <span className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
            <DollarSign className="h-4 w-4" />
          </span>
          <div className="min-w-0">
            <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
              Total estimado
            </p>
            <p className="mt-1 whitespace-nowrap text-lg font-semibold leading-none tabular-nums text-primary">
              {formatCurrency(total)}
            </p>
          </div>
        </div>
      </div>

      {combinedError && (
        <div className="mb-3 flex items-start gap-2 rounded-xl border border-amber-300/50 bg-amber-50 px-3 py-2 text-xs text-amber-900">
          <Info className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
          <span>{combinedError}</span>
        </div>
      )}

      {(loading || tariffLoading || sectionsLoading) && (
        <div className="mb-3 rounded-xl border border-border bg-card px-3 py-2 text-xs text-muted-foreground">
          {loading ? "Cargando costos guardados…" : "Cargando tarifario…"}
        </div>
      )}

      <div className="space-y-4">
        {hasSpecialTariff ? (
          specialSections.map((specialSection) => {
            const sectionCatalog = tariffCatalog.filter(
              (item) => item.section === specialSection.id && getFixedAmount(item) > 0,
            );
            const sectionItems = items.filter((item) =>
              itemBelongsToSpecialSection(item, specialSection),
            );
            const selectedServices = sectionItems.map((item) => item.serviceName);
            const subtotal = sectionItems.reduce(
              (sum, item) => sum + Number(item.amount || 0),
              0,
            );

            return (
              <div
                key={specialSection.id}
                className="space-y-4 rounded-xl border border-primary/20 bg-card p-4"
              >
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <p className="text-sm font-medium">{specialSection.name}</p>
                    <p className="text-xs text-muted-foreground">
                      {specialSection.description ||
                        "Selecciona una o varias piezas. Cada pieza se carga una sola vez con su monto fijo."}
                    </p>
                  </div>
                  <Badge className="w-fit">{specialSection.clientName}</Badge>
                </div>

                <div className="space-y-1.5">
                  <Label>Piezas a cotizar</Label>
                  <SearchableMultiSelect
                    values={selectedServices}
                    options={sectionCatalog.map((item) => item.service)}
                    onValuesChange={(services) =>
                      onSpecialServicesChange(specialSection, services)
                    }
                    placeholder="Seleccionar una o varias piezas…"
                    searchPlaceholder="Buscar pieza…"
                    emptyText="No se encontró esa pieza en este tarifario."
                    disabled={tariffLoading || sectionCatalog.length === 0}
                    summaryLabel="piezas seleccionadas"
                  />
                </div>

                <div className="rounded-xl border border-dashed border-border bg-muted/30 p-3">
                  <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
                    <p className="text-xs font-medium text-foreground">Piezas y montos fijos</p>
                    <p className="text-xs font-semibold text-primary">
                      Subtotal: {formatCurrency(subtotal)}
                    </p>
                  </div>

                  {sectionCatalog.length === 0 ? (
                    <p className="text-xs text-muted-foreground">
                      Este tarifario todavía no tiene piezas activas. Agrégalas desde el módulo
                      Tarifario.
                    </p>
                  ) : (
                    <div className="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
                      {sectionCatalog.map((item) => {
                        const selected = selectedServices.some(
                          (service) =>
                            normalizeOptionKey(service) === normalizeOptionKey(item.service),
                        );

                        return (
                          <div
                            key={item.id}
                            className={cn(
                              "flex items-center justify-between gap-3 rounded-lg border px-2.5 py-2 text-xs",
                              selected
                                ? "border-primary/30 bg-primary/10 text-foreground"
                                : "border-border bg-card text-muted-foreground",
                            )}
                          >
                            <span className="min-w-0 truncate">{item.service}</span>
                            <span className="flex-shrink-0 font-semibold text-foreground">
                              {formatCurrency(getFixedAmount(item))}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>
            );
          })
        ) : (
          <div className="space-y-4 rounded-xl border border-border bg-card p-4">
            <div className="flex items-center justify-between gap-2">
              <div>
                <p className="text-sm font-medium">Agregar desde tarifario general</p>
                <p className="text-xs text-muted-foreground">
                  Referencia flexible. El usuario autorizado decide el monto final.
                </p>
              </div>
              <Badge variant="secondary">Tarifario</Badge>
            </div>

            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              <div className="space-y-1.5">
                <Label>Sección</Label>
                <SearchableSelect
                  value={activeGeneralSection?.name || ""}
                  options={generalSections.map((section) => section.name)}
                  onValueChange={onSectionChange}
                  placeholder="Seleccionar sección…"
                  searchPlaceholder="Buscar sección…"
                  emptyText="No hay secciones generales activas."
                />
              </div>

              <div className="space-y-1.5">
                <Label>Ítem a cobrar</Label>
                <SearchableSelect
                  value={serviceLabel}
                  options={serviceOptions}
                  onValueChange={onServiceChange}
                  placeholder="Seleccionar ítem…"
                  searchPlaceholder="Buscar ítem…"
                  emptyText="No se encontró ese ítem."
                  disabled={!activeGeneralSection}
                />
              </div>

              <div className="space-y-1.5">
                <Label>Tipo de trabajo</Label>
                <SearchableSelect
                  value={selectedWorkTypeLabel}
                  options={selectedItem?.workTypes.map((workType) => workType.label) || []}
                  onValueChange={onWorkTypeChange}
                  placeholder="Seleccionar tipo…"
                  searchPlaceholder="Buscar tipo…"
                  disabled={!selectedItem}
                />
              </div>

              <div className="space-y-1.5">
                <Label>Nivel / referencia</Label>
                <SearchableSelect
                  value={selectedLevelLabel}
                  options={selectedWorkType?.levels.map((item) => item.label) || []}
                  onValueChange={onLevelChange}
                  placeholder="Seleccionar nivel…"
                  searchPlaceholder="Buscar nivel…"
                  disabled={!selectedWorkType}
                />
              </div>
            </div>

            {selectedItem && selectedWorkType && selectedLevel && (
              <div className="rounded-xl border border-dashed border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
                <p>
                  <span className="font-medium text-foreground">Referencia:</span>{" "}
                  {formatTariffRange(selectedLevel)} USD
                  {selectedWorkType.hourReference
                    ? ` · Hora hombre ref.: ${selectedWorkType.hourReference}`
                    : ""}
                </p>
                {selectedItem.notes && <p className="mt-1">{selectedItem.notes}</p>}
                {selectedLevel.hint && <p className="mt-1">{selectedLevel.hint}</p>}
              </div>
            )}

            <div className="grid grid-cols-1 gap-3 md:grid-cols-[220px_minmax(0,1fr)]">
              <div className="space-y-1.5">
                <Label>Monto final</Label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  value={amount}
                  onChange={(event) => setAmount(event.target.value)}
                  placeholder="0.00"
                  disabled={!selectedLevel}
                />
              </div>
              <div className="space-y-1.5">
                <Label>Observación</Label>
                <Textarea
                  value={description}
                  onChange={(event) => setDescription(event.target.value)}
                  placeholder="Ej: más rondas de cambios, piezas adicionales, complejidad especial…"
                  disabled={!selectedLevel}
                  rows={5}
                  className="min-h-[132px] resize-y"
                />
              </div>
            </div>

            <div className="flex justify-end">
              <Button
                type="button"
                onClick={addTariffItem}
                disabled={
                  !selectedItem || !selectedWorkType || !selectedLevel || parseAmount(amount) <= 0
                }
                className="gap-1.5 rounded-full"
              >
                <Plus className="h-4 w-4" />
                Agregar tarifa
              </Button>
            </div>
          </div>
        )}

        {allowManual && (
          <div className="space-y-4 rounded-xl border border-border bg-card p-4">
            <div>
              <p className="text-sm font-medium">
                {manualContext
                  ? `Agregar propuesta o costo manual para ${manualContext.clientName}`
                  : "Agregar costo manual"}
              </p>
              <p className="text-xs text-muted-foreground">
                {manualContext
                  ? "Para propuestas generales, proyectos por concepto o casos no contemplados por pieza."
                  : "Para otros, adicionales o casos fuera del tarifario."}
              </p>
            </div>

            <div className="grid grid-cols-1 gap-3 md:grid-cols-[minmax(0,1fr)_220px]">
              <div className="space-y-1.5">
                <Label>Nombre</Label>
                <Input
                  value={manualName}
                  onChange={(event) => setManualName(event.target.value)}
                  placeholder={
                    manualContext
                      ? `Ej: Propuesta general ${manualContext.clientName}`
                      : "Ej: Piezas adicionales"
                  }
                />
              </div>

              <div className="space-y-1.5">
                <Label>Monto</Label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  value={manualAmount}
                  onChange={(event) => setManualAmount(event.target.value)}
                  placeholder="0.00"
                />
              </div>
            </div>

            <div className="space-y-1.5">
              <Label>Descripción</Label>
              <Textarea
                value={manualDescription}
                onChange={(event) => setManualDescription(event.target.value)}
                placeholder={
                  manualContext
                    ? "Ej: Compendio cotizado por proyecto, no por piezas."
                    : "Ej: Cliente pidió piezas adicionales fuera del paquete."
                }
                rows={4}
                className="min-h-[110px] resize-y"
              />
            </div>

            <div className="flex justify-end">
              <Button
                type="button"
                variant="outline"
                onClick={addManualItem}
                disabled={parseAmount(manualAmount) <= 0}
                className="w-full gap-1.5 rounded-full sm:w-auto sm:min-w-[240px]"
              >
                <Plus className="h-4 w-4" />
                Agregar costo manual
              </Button>
            </div>
          </div>
        )}
      </div>

      <Separator className="my-4" />

      <div className="space-y-2">
        <div className="flex items-center justify-between gap-2">
          <p className="text-sm font-medium">Costos agregados</p>
          <p className="text-xs text-muted-foreground">{items.length} línea(s)</p>
        </div>

        {items.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border bg-card/70 px-3 py-3 text-sm text-muted-foreground">
            Aún no hay costos agregados. Usa el tarifario disponible o agrega un monto manual.
          </div>
        ) : (
          <div className="space-y-2">
            {items.map((item, index) => {
              const specialSection = sections.find(
                (section) => section.id === item.tariffSectionId && section.scope === "client",
              );
              const legacyWmc = !specialSection && specialSections.find((section) =>
                isLegacyWmcItem(item, section),
              );
              const itemSpecialSection = specialSection || legacyWmc;

              return (
                <div
                  key={`${item.source}-${item.serviceName}-${index}`}
                  className="flex flex-col gap-2 rounded-xl border border-border bg-card px-3 py-3 sm:flex-row sm:items-start sm:justify-between"
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <Badge variant={item.source === "manual" ? "outline" : "secondary"}>
                        {item.source === "manual"
                          ? "Manual"
                          : itemSpecialSection
                            ? itemSpecialSection.clientName
                            : "Tarifario"}
                      </Badge>
                      <p className="text-sm font-medium">{item.serviceName}</p>
                    </div>

                    <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
                      {item.category && <span>{item.category}</span>}
                      {item.workType && <span>{item.workType}</span>}
                      {item.complexityLevel && <span>{item.complexityLevel}</span>}
                      {item.referenceLabel && <span>Ref.: {item.referenceLabel}</span>}
                    </div>

                    {item.description && (
                      <p className="mt-2 text-sm text-muted-foreground">{item.description}</p>
                    )}
                  </div>

                  <div className="flex items-center justify-between gap-3 sm:flex-col sm:items-end">
                    <p className="text-sm font-semibold text-foreground">
                      {formatCurrency(Number(item.amount || 0))}
                    </p>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeItem(index)}
                      className={cn(
                        "h-8 rounded-full px-2 text-muted-foreground hover:text-destructive",
                      )}
                    >
                      <Trash2 className="mr-1 h-3.5 w-3.5" />
                      Quitar
                    </Button>
                  </div>
                </div>
              );
            })}

            <div className="flex items-center justify-end gap-2 rounded-xl bg-primary/10 px-3 py-2 text-primary">
              <DollarSign className="h-4 w-4" />
              <span className="text-sm font-semibold">
                Total interno estimado: {formatCurrency(total)}
              </span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
