import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Autocomplete,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import styled from "styled-components";
import { searchClientes } from "../../api/clientes.service";
import {
  useCrearCompraAsistidaMutation,
  useEditarCompraAsistidaMutation,
} from "../../tanstack/CompraAsistidaStack";
import { formatMoney } from "../../utils/formatMoney";

const ITEM_VACIO = () => ({
  key: Math.random(),
  descripcion: "",
  url_producto: "",
  proveedor_china: "",
  cantidad: 1,
  precio_usd: 0,
});

export default function NuevaCompraAsistidaForm({
  open,
  onClose,
  compraExistente,
}) {
  const isEdit = !!compraExistente;

  // Estado del formulario
  const [cliente, setCliente] = useState(null);
  const [clienteOptions, setClienteOptions] = useState([]);
  const [clienteSearch, setClienteSearch] = useState("");
  const [clienteLoading, setClienteLoading] = useState(false);

  const [cotizacion, setCotizacion] = useState(7500);
  const [servicio, setServicio] = useState(0);
  const [logistica, setLogistica] = useState(0);
  const [comision, setComision] = useState(0);
  const [notas, setNotas] = useState("");
  const [fechaEntrega, setFechaEntrega] = useState("");
  const [items, setItems] = useState([ITEM_VACIO()]);

  const crearMutation = useCrearCompraAsistidaMutation();
  const editarMutation = useEditarCompraAsistidaMutation();

  // Pre-llenar si es edición
  useEffect(() => {
    if (compraExistente) {
      setCotizacion(Number(compraExistente.cotizacion_usd_gs) || 7500);
      setServicio(Number(compraExistente.servicio_gs) || 0);
      setLogistica(Number(compraExistente.logistica_gs) || 0);
      setComision(Number(compraExistente.comision_gs) || 0);
      setNotas(compraExistente.notas || "");
      setFechaEntrega(
        compraExistente.fecha_entrega_estimada
          ? compraExistente.fecha_entrega_estimada.substring(0, 10)
          : "",
      );
      if (compraExistente.items?.length) {
        setItems(
          compraExistente.items.map((i) => ({
            key: Math.random(),
            descripcion: i.descripcion,
            url_producto: i.url_producto || "",
            proveedor_china: i.proveedor_china || "",
            cantidad: i.cantidad,
            precio_usd: Number(i.precio_usd),
          })),
        );
      }
      if (compraExistente.cliente) {
        setCliente(compraExistente.cliente);
        setClienteOptions([compraExistente.cliente]);
      }
    }
  }, [compraExistente]);

  // Debounce búsqueda de cliente
  useEffect(() => {
    if (!clienteSearch || clienteSearch.length < 2) {
      setClienteOptions([]);
      return;
    }
    let active = true;
    setClienteLoading(true);
    searchClientes(clienteSearch).then((res) => {
      if (active) {
        setClienteOptions(res);
        setClienteLoading(false);
      }
    });
    return () => {
      active = false;
    };
  }, [clienteSearch]);

  const subtotalUsd = useMemo(
    () =>
      items.reduce(
        (s, i) => s + Number(i.cantidad || 0) * Number(i.precio_usd || 0),
        0,
      ),
    [items],
  );

  const subtotalGs = subtotalUsd * Number(cotizacion || 0);
  const totalGs =
    subtotalGs + Number(servicio || 0) + Number(logistica || 0) + Number(comision || 0);

  const updateItem = (idx, field, value) => {
    setItems((prev) =>
      prev.map((it, i) => (i === idx ? { ...it, [field]: value } : it)),
    );
  };

  const addItem = () => setItems((prev) => [...prev, ITEM_VACIO()]);

  const removeItem = (idx) => {
    if (items.length === 1) return;
    setItems((prev) => prev.filter((_, i) => i !== idx));
  };

  const getClienteLabel = (opt) => {
    if (!opt) return "";
    return (
      opt.personas?.razon_social ||
      opt.nombre_fantasia ||
      opt.ruc ||
      ""
    );
  };

  const buildPayload = () => ({
    cliente_id: cliente?.id ?? null,
    cotizacion_usd_gs: Number(cotizacion),
    servicio_gs: Number(servicio),
    logistica_gs: Number(logistica),
    comision_gs: Number(comision),
    notas: notas || null,
    fecha_entrega_estimada: fechaEntrega || null,
    items: items.map((it, idx) => ({
      descripcion: it.descripcion,
      url_producto: it.url_producto || null,
      proveedor_china: it.proveedor_china || null,
      cantidad: Number(it.cantidad),
      precio_usd: Number(it.precio_usd),
      orden: idx,
    })),
  });

  const handleSubmit = () => {
    const payload = buildPayload();
    if (payload.items.some((i) => !i.descripcion)) {
      alert("Todos los ítems deben tener descripción");
      return;
    }
    if (isEdit) {
      editarMutation.mutate(
        { id: compraExistente.id, data: payload },
        { onSuccess: onClose },
      );
    } else {
      crearMutation.mutate(payload, { onSuccess: onClose });
    }
  };

  const isPending = crearMutation.isPending || editarMutation.isPending;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="lg" fullWidth>
      <DialogTitle
        sx={{
          bgcolor: "#0f172a",
          color: "#f1f5f9",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Typography fontWeight={700} fontSize={18}>
          {isEdit ? "Editar Compra Asistida" : "Nueva Compra Asistida"}
        </Typography>
        <IconButton onClick={onClose} sx={{ color: "#94a3b8" }}>
          <Icon icon="mdi:close" />
        </IconButton>
      </DialogTitle>

      <DialogContent sx={{ bgcolor: "#0f172a", p: 0 }}>
        <Layout>
          {/* Panel izquierdo */}
          <LeftPanel>
            {/* Datos del pedido */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:file-document-outline" />
                Datos del Pedido
              </SectionTitle>
              <Box display="flex" gap={2} flexWrap="wrap">
                <TextField
                  label="Cotización USD → Gs"
                  type="number"
                  size="small"
                  value={cotizacion}
                  onChange={(e) => setCotizacion(e.target.value)}
                  sx={{ width: 180 }}
                  inputProps={{ min: 0 }}
                />
                <TextField
                  label="Fecha entrega estimada"
                  type="date"
                  size="small"
                  value={fechaEntrega}
                  onChange={(e) => setFechaEntrega(e.target.value)}
                  InputLabelProps={{ shrink: true }}
                  sx={{ width: 200 }}
                />
                <TextField
                  label="Notas"
                  size="small"
                  value={notas}
                  onChange={(e) => setNotas(e.target.value)}
                  multiline
                  rows={2}
                  fullWidth
                />
              </Box>
            </Section>

            {/* Cliente */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:account-outline" />
                Cliente
              </SectionTitle>
              <Autocomplete
                options={clienteOptions}
                getOptionLabel={getClienteLabel}
                value={cliente}
                onChange={(_, v) => setCliente(v)}
                onInputChange={(_, v) => setClienteSearch(v)}
                loading={clienteLoading}
                noOptionsText={
                  clienteSearch.length < 2
                    ? "Escribí al menos 2 caracteres"
                    : "Sin resultados"
                }
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="Buscar cliente por nombre o RUC"
                    size="small"
                    InputProps={{
                      ...params.InputProps,
                      endAdornment: (
                        <>
                          {clienteLoading && (
                            <CircularProgress color="inherit" size={16} />
                          )}
                          {params.InputProps.endAdornment}
                        </>
                      ),
                    }}
                  />
                )}
              />
            </Section>

            {/* Items */}
            <Section>
              <SectionTitle>
                <Icon icon="mdi:package-variant-closed" />
                Items del Pedido
              </SectionTitle>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ color: "#94a3b8", width: "30%" }}>
                      Descripción *
                    </TableCell>
                    <TableCell sx={{ color: "#94a3b8" }}>URL</TableCell>
                    <TableCell sx={{ color: "#94a3b8" }}>
                      Proveedor China
                    </TableCell>
                    <TableCell sx={{ color: "#94a3b8", width: 70 }}>
                      Cant.
                    </TableCell>
                    <TableCell sx={{ color: "#94a3b8", width: 100 }}>
                      Precio USD
                    </TableCell>
                    <TableCell sx={{ color: "#94a3b8", width: 40 }} />
                  </TableRow>
                </TableHead>
                <TableBody>
                  {items.map((item, idx) => (
                    <TableRow key={item.key}>
                      <TableCell>
                        <TextField
                          size="small"
                          placeholder="Descripción del producto"
                          value={item.descripcion}
                          onChange={(e) =>
                            updateItem(idx, "descripcion", e.target.value)
                          }
                          fullWidth
                          required
                        />
                      </TableCell>
                      <TableCell>
                        <TextField
                          size="small"
                          placeholder="https://..."
                          value={item.url_producto}
                          onChange={(e) =>
                            updateItem(idx, "url_producto", e.target.value)
                          }
                          fullWidth
                        />
                      </TableCell>
                      <TableCell>
                        <TextField
                          size="small"
                          placeholder="Aliexpress, 1688..."
                          value={item.proveedor_china}
                          onChange={(e) =>
                            updateItem(idx, "proveedor_china", e.target.value)
                          }
                          fullWidth
                        />
                      </TableCell>
                      <TableCell>
                        <TextField
                          size="small"
                          type="number"
                          value={item.cantidad}
                          onChange={(e) =>
                            updateItem(idx, "cantidad", e.target.value)
                          }
                          inputProps={{ min: 1 }}
                          fullWidth
                        />
                      </TableCell>
                      <TableCell>
                        <TextField
                          size="small"
                          type="number"
                          value={item.precio_usd}
                          onChange={(e) =>
                            updateItem(idx, "precio_usd", e.target.value)
                          }
                          inputProps={{ min: 0, step: "0.01" }}
                          fullWidth
                        />
                      </TableCell>
                      <TableCell>
                        <IconButton
                          size="small"
                          onClick={() => removeItem(idx)}
                          disabled={items.length === 1}
                          sx={{ color: "#ef4444" }}
                        >
                          <Icon icon="mdi:trash-can-outline" />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              <Button
                size="small"
                startIcon={<Icon icon="mdi:plus" />}
                onClick={addItem}
                sx={{ mt: 1, color: "#3b82f6" }}
              >
                Agregar ítem
              </Button>
            </Section>
          </LeftPanel>

          {/* Panel derecho — Resumen */}
          <RightPanel>
            <SectionTitle>
              <Icon icon="mdi:calculator-variant-outline" />
              Resumen
            </SectionTitle>

            <ResumenRow>
              <span>Subtotal USD</span>
              <strong>{subtotalUsd.toFixed(2)} USD</strong>
            </ResumenRow>
            <ResumenRow>
              <span>Cotización</span>
              <strong>
                {Number(cotizacion).toLocaleString("es-PY")} Gs/USD
              </strong>
            </ResumenRow>
            <ResumenRow>
              <span>Subtotal en Gs</span>
              <strong>{formatMoney(subtotalGs, "PYG")}</strong>
            </ResumenRow>

            <Divider />

            <ResumenInput>
              <TextField
                label="Servicio (Gs)"
                type="number"
                size="small"
                value={servicio}
                onChange={(e) => setServicio(e.target.value)}
                fullWidth
                inputProps={{ min: 0 }}
              />
            </ResumenInput>
            <ResumenInput>
              <TextField
                label="Logística (Gs)"
                type="number"
                size="small"
                value={logistica}
                onChange={(e) => setLogistica(e.target.value)}
                fullWidth
                inputProps={{ min: 0 }}
              />
            </ResumenInput>
            <ResumenInput>
              <TextField
                label="Comisión (Gs)"
                type="number"
                size="small"
                value={comision}
                onChange={(e) => setComision(e.target.value)}
                fullWidth
                inputProps={{ min: 0 }}
              />
            </ResumenInput>

            <Divider />

            <TotalRow>
              <span>TOTAL GS</span>
              <span>{formatMoney(totalGs, "PYG")}</span>
            </TotalRow>

            <Box mt={3}>
              <Button
                variant="contained"
                fullWidth
                size="large"
                disabled={isPending}
                onClick={handleSubmit}
                sx={{
                  bgcolor: "#f88533",
                  "&:hover": { bgcolor: "#e07320" },
                  fontWeight: 700,
                  fontSize: 15,
                  py: 1.5,
                }}
              >
                {isPending ? (
                  <CircularProgress size={20} color="inherit" />
                ) : isEdit ? (
                  "Guardar Cambios"
                ) : (
                  "Crear Pedido"
                )}
              </Button>
            </Box>
          </RightPanel>
        </Layout>
      </DialogContent>
    </Dialog>
  );
}

// --- Styled Components ---

const Layout = styled.div`
  display: flex;
  gap: 0;
  min-height: 500px;
  @media (max-width: 900px) {
    flex-direction: column;
  }
`;

const LeftPanel = styled.div`
  flex: 7;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  overflow-y: auto;
`;

const RightPanel = styled.div`
  flex: 3;
  background: #1e293b;
  border-left: 1px solid #334155;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 260px;
`;

const Section = styled.div`
  background: #1e293b;
  border: 1px solid #334155;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const SectionTitle = styled.div`
  color: #3b82f6;
  font-weight: 700;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
`;

const ResumenRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #cbd5e1;
  font-size: 14px;
`;

const ResumenInput = styled.div`
  margin: 2px 0;
`;

const Divider = styled.hr`
  border: none;
  border-top: 1px solid #334155;
  margin: 4px 0;
`;

const TotalRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #f1f5f9;
  font-weight: 700;
  font-size: 18px;
`;
