import { Icon } from "@iconify/react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import styled from "styled-components";
import { getBancardConfig, upsertBancardConfig } from "../../api/bancard.service";

const Card = styled.div`
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 12px;
  padding: 24px;
  max-width: 600px;
`;

const Title = styled.h3`
  margin: 0 0 20px;
  font-size: 15px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const FieldGroup = styled.div`
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 4px;
`;

const Label = styled.label`
  font-size: 12px;
  color: ${({ theme }) => theme.textSecondary};
  font-weight: 500;
`;

const Input = styled.input`
  padding: 8px 12px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 7px;
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.color1};
  font-size: 13px;
  &:focus { outline: none; border-color: ${({ theme }) => theme.primary}; }
`;

const Select = styled.select`
  padding: 8px 12px;
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 7px;
  background: ${({ theme }) => theme.bg3};
  color: ${({ theme }) => theme.color1};
  font-size: 13px;
`;

const Row = styled.div`
  display: flex;
  gap: 16px;
  & > * { flex: 1; }
`;

const Btn = styled.button`
  padding: 9px 18px;
  border-radius: 8px;
  border: none;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  background: ${({ $variant, theme }) => $variant === "primary" ? theme.primary : theme.bg3};
  color: ${({ $variant, theme }) => $variant === "primary" ? "#fff" : theme.color1};
  &:disabled { opacity: 0.5; cursor: not-allowed; }
`;

const HintText = styled.p`
  font-size: 11px;
  color: ${({ theme }) => theme.textSecondary};
  margin: 2px 0 0;
`;

const StatusBadge = styled.span`
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  background: ${({ $active }) => ($active ? "#4caf5022" : "#f4433622")};
  color: ${({ $active }) => ($active ? "#4caf50" : "#f44336")};
`;

const emptyForm = {
  ambiente: "staging",
  public_key: "",
  private_key: "",
  return_url_base: "",
  cancel_url_base: "",
  webhook_secret: "",
  porcentaje_comision_credito: "3.50",
  porcentaje_comision_debito: "2.50",
  timeout_segundos: "1800",
  activo: false,
};

export function BancardConfigPanel() {
  const [config, setConfig] = useState(null);
  const [form, setForm] = useState({ ...emptyForm });
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getBancardConfig()
      .then((data) => {
        setConfig(data);
        if (data) {
          setForm({
            ambiente: data.ambiente ?? "staging",
            public_key: data.public_key ?? "",
            private_key: "",
            return_url_base: data.return_url_base ?? "",
            cancel_url_base: data.cancel_url_base ?? "",
            webhook_secret: data.webhook_secret ?? "",
            porcentaje_comision_credito: String(data.porcentaje_comision_credito ?? "3.50"),
            porcentaje_comision_debito: String(data.porcentaje_comision_debito ?? "2.50"),
            timeout_segundos: String(data.timeout_segundos ?? "1800"),
            activo: data.activo ?? false,
          });
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = {
        ambiente: form.ambiente,
        public_key: form.public_key || undefined,
        private_key: form.private_key || undefined,
        return_url_base: form.return_url_base || undefined,
        cancel_url_base: form.cancel_url_base || undefined,
        webhook_secret: form.webhook_secret || undefined,
        porcentaje_comision_credito: Number(form.porcentaje_comision_credito),
        porcentaje_comision_debito: Number(form.porcentaje_comision_debito),
        timeout_segundos: Number(form.timeout_segundos),
        activo: form.activo,
      };
      const updated = await upsertBancardConfig(payload);
      setConfig(updated);
      setForm((f) => ({ ...f, private_key: "" }));
      toast.success("Configuración Bancard guardada");
    } catch (err) {
      toast.error(err.response?.data?.message || "Error al guardar");
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <Card><p style={{ fontSize: 13, color: "#888" }}>Cargando…</p></Card>;

  return (
    <Card>
      <Title>
        <Icon icon="mdi:credit-card-settings-outline" />
        Configuración Bancard VPOS
        {config && (
          <StatusBadge $active={config.activo}>
            <Icon icon={config.activo ? "mdi:check-circle" : "mdi:close-circle"} />
            {config.activo ? "Activo" : "Inactivo"}
          </StatusBadge>
        )}
      </Title>

      <FieldGroup>
        <Label>Ambiente</Label>
        <Select value={form.ambiente} onChange={(e) => set("ambiente", e.target.value)}>
          <option value="staging">Staging (pruebas)</option>
          <option value="produccion">Producción</option>
        </Select>
      </FieldGroup>

      <Row>
        <FieldGroup>
          <Label>Public Key</Label>
          <Input value={form.public_key} onChange={(e) => set("public_key", e.target.value)} placeholder="public_key de Bancard" />
        </FieldGroup>
        <FieldGroup>
          <Label>Private Key {config?.tiene_private_key ? "(ya configurada)" : ""}</Label>
          <Input
            type="password"
            value={form.private_key}
            onChange={(e) => set("private_key", e.target.value)}
            placeholder={config?.tiene_private_key ? "Dejar vacío para no cambiar" : "private_key de Bancard"}
          />
          <HintText>Se cifra con AES-256-CBC antes de guardarse</HintText>
        </FieldGroup>
      </Row>

      <Row>
        <FieldGroup>
          <Label>Return URL Base</Label>
          <Input value={form.return_url_base} onChange={(e) => set("return_url_base", e.target.value)} placeholder="https://…/pay/result" />
        </FieldGroup>
        <FieldGroup>
          <Label>Cancel URL Base</Label>
          <Input value={form.cancel_url_base} onChange={(e) => set("cancel_url_base", e.target.value)} placeholder="https://…/pay/cancel" />
        </FieldGroup>
      </Row>

      <FieldGroup>
        <Label>Webhook Secret</Label>
        <Input value={form.webhook_secret} onChange={(e) => set("webhook_secret", e.target.value)} placeholder="Secreto para validar webhooks" />
      </FieldGroup>

      <Row>
        <FieldGroup>
          <Label>Comisión Crédito (%)</Label>
          <Input type="number" step="0.01" value={form.porcentaje_comision_credito} onChange={(e) => set("porcentaje_comision_credito", e.target.value)} />
        </FieldGroup>
        <FieldGroup>
          <Label>Comisión Débito (%)</Label>
          <Input type="number" step="0.01" value={form.porcentaje_comision_debito} onChange={(e) => set("porcentaje_comision_debito", e.target.value)} />
        </FieldGroup>
        <FieldGroup>
          <Label>Timeout (seg)</Label>
          <Input type="number" value={form.timeout_segundos} onChange={(e) => set("timeout_segundos", e.target.value)} />
        </FieldGroup>
      </Row>

      <FieldGroup>
        <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", fontSize: 13 }}>
          <input type="checkbox" checked={form.activo} onChange={(e) => set("activo", e.target.checked)} />
          Módulo Bancard activo
        </label>
      </FieldGroup>

      <div style={{ marginTop: 8 }}>
        <Btn $variant="primary" onClick={handleSave} disabled={saving}>
          <Icon icon={saving ? "mdi:loading" : "mdi:content-save"} />
          {saving ? "Guardando…" : "Guardar Configuración"}
        </Btn>
      </div>
    </Card>
  );
}
