import { useState, useCallback, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import {
  offerCustomersOptions,
  type Customer,
  type CustomField,
} from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import AresAdornment, { type AresCompany } from "../components/AresLookup";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  CheckboxField,
  StatusChip,
  PageHeader,
  PageEnter,
  FilterBar,
  EmptyState,
  LoadingState,
  type DataColumn,
} from "../ui";

const API_BASE = "/api/admin";

const DEFAULT_CUSTOMER_FIELD_ORDER = [
  "street",
  "city_postal",
  "country",
  "company_id",
  "vat_id",
];

const CUSTOMER_FIELD_LABELS: Record<string, string> = {
  street: "Ulice",
  city_postal: "Město + PSČ",
  country: "Země",
  company_id: "IČO",
  vat_id: "DIČ",
};

interface CustomerForm {
  name: string;
  street: string;
  city: string;
  postal_code: string;
  country: string;
  company_id: string;
  vat_id: string;
}

const PlusIcon = (
  <svg
    width="20"
    height="20"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <line x1="12" y1="5" x2="12" y2="19" />
    <line x1="5" y1="12" x2="19" y2="12" />
  </svg>
);
const SmallPlusIcon = (
  <svg
    width="14"
    height="14"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <line x1="12" y1="5" x2="12" y2="19" />
    <line x1="5" y1="12" x2="19" y2="12" />
  </svg>
);
const EditIcon = (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
  </svg>
);
const DeleteIcon = (
  <svg
    width="18"
    height="18"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <polyline points="3 6 5 6 21 6" />
    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
  </svg>
);
const RemoveIcon = (
  <svg
    width="14"
    height="14"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <line x1="18" y1="6" x2="6" y2="18" />
    <line x1="6" y1="6" x2="18" y2="18" />
  </svg>
);
const UpIcon = (
  <svg
    width="12"
    height="12"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M18 15l-6-6-6 6" />
  </svg>
);
const DownIcon = (
  <svg
    width="12"
    height="12"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M6 9l6 6 6-6" />
  </svg>
);

export default function OffersCustomers() {
  const alert = useAlert();
  const { hasPermission } = useAuth();
  const { data: customers = [], isPending } = useQuery(offerCustomersOptions());
  const [search, setSearch] = useState("");

  const [showModal, setShowModal] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<CustomerForm>({
    name: "",
    street: "",
    city: "",
    postal_code: "",
    country: "",
    company_id: "",
    vat_id: "",
  });
  const [customFields, setCustomFields] = useState<CustomField[]>([]);
  const customFieldKeyCounter = useRef(0);
  const [fieldOrder, setFieldOrder] = useState<string[]>([
    ...DEFAULT_CUSTOMER_FIELD_ORDER,
  ]);

  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    customer: Customer | null;
  }>({ show: false, customer: null });
  const [deleting, setDeleting] = useState(false);

  const submitMutation = useApiMutation<
    CustomerForm & {
      custom_fields: Array<{
        name: string;
        value: string;
        showLabel?: boolean;
      }>;
      customer_field_order: string[];
    },
    { message?: string; error?: string }
  >({
    url: () =>
      editingCustomer
        ? `${API_BASE}/customers/${editingCustomer.id}`
        : `${API_BASE}/customers`,
    method: () => (editingCustomer ? "PUT" : "POST"),
    // Broad domain key — covers the ["offers","customers"] picker query too.
    invalidate: ["offers"],
    onSuccess: (data) => {
      closeModal();
      setTimeout(
        () => alert.success(data?.message || "Zákazník byl uložen"),
        300,
      );
    },
  });

  const deleteMutation = useApiMutation<
    number,
    { message?: string; error?: string }
  >({
    url: (id) => `${API_BASE}/customers/${id}`,
    method: () => "DELETE",
    // Broad domain key — covers the ["offers","customers"] picker query too.
    invalidate: ["offers"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, customer: null });
      alert.success(data?.message || "Zákazník byl smazán");
    },
  });

  const getFullFieldOrder = useCallback(() => {
    const allBuiltIn = [...DEFAULT_CUSTOMER_FIELD_ORDER];
    const order = [...fieldOrder].filter((k) => k !== "name");

    for (const f of allBuiltIn) {
      if (!order.includes(f)) order.push(f);
    }

    for (let i = 0; i < customFields.length; i++) {
      const key = `custom_${i}`;
      if (!order.includes(key)) order.push(key);
    }

    return order.filter((key) => {
      if (key.startsWith("custom_")) {
        const idx = parseInt(key.split("_")[1], 10);
        return idx < customFields.length;
      }
      return true;
    });
  }, [fieldOrder, customFields]);

  const moveField = (index: number, direction: number) => {
    const order = getFullFieldOrder();
    const newIndex = index + direction;
    if (newIndex < 0 || newIndex >= order.length) return;
    const updated = [...order];
    [updated[index], updated[newIndex]] = [updated[newIndex], updated[index]];
    setFieldOrder(updated);
  };

  const getFieldDisplayName = (key: string) => {
    if (CUSTOMER_FIELD_LABELS[key]) return CUSTOMER_FIELD_LABELS[key];
    if (key.startsWith("custom_")) {
      const idx = parseInt(key.split("_")[1], 10);
      const cf = customFields[idx];
      if (cf)
        return cf.name
          ? `${cf.name}: ${cf.value || "..."}`
          : cf.value || `Vlastní pole ${idx + 1}`;
    }
    return key;
  };

  // ARES prefill — overwrite the company fields with registry data (the
  // button is an explicit user action, so overwriting is the expected UX).
  const fillFromAres = (c: AresCompany) => {
    setForm((prev) => ({
      ...prev,
      name: c.name || prev.name,
      street: c.street,
      city: c.city,
      postal_code: c.postal_code,
      country: c.country,
      company_id: c.ico,
      vat_id: c.dic || "",
    }));
  };

  const openCreateModal = () => {
    setEditingCustomer(null);
    setForm({
      name: "",
      street: "",
      city: "",
      postal_code: "",
      country: "",
      company_id: "",
      vat_id: "",
    });
    setCustomFields([]);
    setFieldOrder([...DEFAULT_CUSTOMER_FIELD_ORDER]);
    setShowModal(true);
  };

  const openEditModal = (customer: Customer) => {
    setEditingCustomer(customer);
    setForm({
      name: customer.name || "",
      street: customer.street || "",
      city: customer.city || "",
      postal_code: customer.postal_code || "",
      country: customer.country || "",
      company_id: customer.company_id || "",
      vat_id: customer.vat_id || "",
    });
    const cf =
      Array.isArray(customer.custom_fields) && customer.custom_fields.length > 0
        ? customer.custom_fields.map((f) => ({
            ...f,
            _key: `cf-${++customFieldKeyCounter.current}`,
          }))
        : [];
    setCustomFields(cf);
    if (
      Array.isArray(customer.customer_field_order) &&
      customer.customer_field_order.length > 0
    ) {
      setFieldOrder(customer.customer_field_order);
    } else {
      setFieldOrder([...DEFAULT_CUSTOMER_FIELD_ORDER]);
    }
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setEditingCustomer(null);
  };

  const handleSubmit = async () => {
    if (!form.name.trim()) {
      alert.error("Název zákazníka je povinný");
      return;
    }

    const payload = {
      ...form,
      custom_fields: customFields
        .filter((f) => f.name.trim() || f.value.trim())
        .map((f) => ({
          name: f.name,
          value: f.value,
          showLabel: f.showLabel,
        })),
      customer_field_order: getFullFieldOrder(),
    };

    setSaving(true);
    try {
      await submitMutation.mutateAsync(payload);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.customer) return;

    setDeleting(true);
    try {
      await deleteMutation.mutateAsync(deleteConfirm.customer.id);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setDeleting(false);
    }
  };

  if (!hasPermission("customers.view")) return <Forbidden />;

  const filteredCustomers = search
    ? customers.filter(
        (c) =>
          (c.name || "").toLowerCase().includes(search.toLowerCase()) ||
          (c.company_id || "").includes(search) ||
          (c.city || "").toLowerCase().includes(search.toLowerCase()),
      )
    : customers;

  const fullFieldOrder = getFullFieldOrder();

  if (isPending) {
    return <LoadingState />;
  }

  const columns: DataColumn<Customer>[] = [
    {
      key: "name",
      header: "Název",
      width: "26%",
      render: (c) => (
        <Box>
          <Box sx={{ fontWeight: 500, color: "text.primary" }}>{c.name}</Box>
          {c.street && (
            <Box sx={{ fontSize: "11px", color: "text.disabled" }}>
              {c.street}
            </Box>
          )}
        </Box>
      ),
    },
    {
      key: "city",
      header: "Město",
      width: "18%",
      render: (c) => c.city || "—",
    },
    {
      key: "company_id",
      header: "IČO",
      width: "13%",
      mono: true,
      render: (c) => c.company_id || "—",
    },
    {
      key: "vat_id",
      header: "DIČ",
      width: "13%",
      mono: true,
      render: (c) => c.vat_id || "—",
    },
    {
      key: "quotation_count",
      header: "Nabídky",
      width: "10%",
      render: (c) => (
        <StatusChip label={String(c.quotation_count || 0)} color="info" />
      ),
    },
    {
      key: "actions",
      header: "Akce",
      width: "10%",
      align: "right",
      render: (c) => {
        const cannotDelete = c.quotation_count > 0;
        return (
          <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
            {hasPermission("customers.edit") && (
              <IconButton
                size="small"
                onClick={() => openEditModal(c)}
                aria-label="Upravit"
                title="Upravit"
              >
                {EditIcon}
              </IconButton>
            )}
            {hasPermission("customers.delete") && (
              // Disabled buttons don't fire title/tooltip, so wrap in a titled
              // span when delete is blocked (customer still has quotations).
              <Box
                component="span"
                title={
                  cannotDelete ? "Nelze smazat zákazníka s nabídkami" : "Smazat"
                }
              >
                <IconButton
                  size="small"
                  color="error"
                  onClick={() => setDeleteConfirm({ show: true, customer: c })}
                  aria-label={
                    cannotDelete
                      ? "Nelze smazat zákazníka s nabídkami"
                      : "Smazat"
                  }
                  disabled={cannotDelete}
                >
                  {DeleteIcon}
                </IconButton>
              </Box>
            )}
          </Box>
        );
      },
    },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Zákazníci"
        subtitle="Správa zákazníků pro nabídky"
        actions={
          hasPermission("customers.create") ? (
            <Button startIcon={PlusIcon} onClick={openCreateModal}>
              Přidat zákazníka
            </Button>
          ) : undefined
        }
      />

      <FilterBar>
        <Box sx={{ flex: "1 1 320px" }}>
          <TextField
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Hledat zákazníky..."
            fullWidth
          />
        </Box>
      </FilterBar>

      <Card>
        <DataTable<Customer>
          columns={columns}
          rows={filteredCustomers}
          rowKey={(c) => c.id}
          empty={
            <EmptyState
              title={
                search
                  ? "Žádní zákazníci odpovídající hledání."
                  : "Zatím nejsou žádní zákazníci."
              }
              action={
                !search && hasPermission("customers.create") ? (
                  <Button startIcon={PlusIcon} onClick={openCreateModal}>
                    Přidat prvního zákazníka
                  </Button>
                ) : undefined
              }
            />
          }
        />
      </Card>

      {/* Create/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={closeModal}
        onSubmit={handleSubmit}
        title={editingCustomer ? "Upravit zákazníka" : "Nový zákazník"}
        submitText={editingCustomer ? "Uložit změny" : "Vytvořit zákazníka"}
        loading={saving}
        maxWidth="md"
      >
        <Field label="Název" required>
          <TextField
            value={form.name}
            onChange={(e) =>
              setForm((prev) => ({ ...prev, name: e.target.value }))
            }
            placeholder="Název firmy / jméno"
            InputProps={{
              endAdornment: (
                <AresAdornment
                  mode="name"
                  query={form.name}
                  onFill={fillFromAres}
                />
              ),
            }}
          />
        </Field>
        <Field label="Ulice">
          <TextField
            value={form.street}
            onChange={(e) =>
              setForm((prev) => ({ ...prev, street: e.target.value }))
            }
          />
        </Field>
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
            gap: 2,
          }}
        >
          <Field label="Město">
            <TextField
              value={form.city}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, city: e.target.value }))
              }
            />
          </Field>
          <Field label="PSČ">
            <TextField
              value={form.postal_code}
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  postal_code: e.target.value,
                }))
              }
            />
          </Field>
        </Box>
        <Field label="Země">
          <TextField
            value={form.country}
            onChange={(e) =>
              setForm((prev) => ({ ...prev, country: e.target.value }))
            }
          />
        </Field>
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
            gap: 2,
          }}
        >
          <Field label="IČO">
            <TextField
              value={form.company_id}
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  company_id: e.target.value,
                }))
              }
              InputProps={{
                endAdornment: (
                  <AresAdornment
                    mode="ico"
                    query={form.company_id}
                    onFill={fillFromAres}
                  />
                ),
              }}
            />
          </Field>
          <Field label="DIČ">
            <TextField
              value={form.vat_id}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, vat_id: e.target.value }))
              }
            />
          </Field>
        </Box>

        {/* Dynamic custom fields */}
        <Box sx={{ mt: 0.5 }}>
          <Typography
            variant="body2"
            sx={{
              display: "block",
              mb: 0.5,
              fontWeight: 600,
              color: "text.secondary",
            }}
          >
            Vlastní pole
          </Typography>
          {customFields.map((field, idx) => (
            <Box key={field._key} sx={{ mb: 1 }}>
              <Box
                sx={{
                  display: "grid",
                  gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                  gap: 2,
                  alignItems: "flex-start",
                }}
              >
                <TextField
                  label={idx === 0 ? "Název" : undefined}
                  value={field.name}
                  onChange={(e) => {
                    const updated = [...customFields];
                    updated[idx] = {
                      ...updated[idx],
                      name: e.target.value,
                    };
                    setCustomFields(updated);
                  }}
                  placeholder="Např. Kontakt"
                />
                <Box
                  sx={{
                    display: "flex",
                    gap: 0.5,
                    alignItems: idx === 0 ? "flex-end" : "center",
                  }}
                >
                  <TextField
                    label={idx === 0 ? "Hodnota" : undefined}
                    value={field.value}
                    onChange={(e) => {
                      const updated = [...customFields];
                      updated[idx] = {
                        ...updated[idx],
                        value: e.target.value,
                      };
                      setCustomFields(updated);
                    }}
                    sx={{ flex: 1 }}
                  />
                  <IconButton
                    size="small"
                    color="error"
                    onClick={() => {
                      const key = `custom_${idx}`;
                      setFieldOrder((prev) => {
                        return prev
                          .filter((k) => k !== key)
                          .map((k) => {
                            if (k.startsWith("custom_")) {
                              const ki = parseInt(k.split("_")[1], 10);
                              if (ki > idx) return `custom_${ki - 1}`;
                            }
                            return k;
                          });
                      });
                      setCustomFields(customFields.filter((_, i) => i !== idx));
                    }}
                    title="Odebrat pole"
                    aria-label="Odebrat pole"
                  >
                    {RemoveIcon}
                  </IconButton>
                </Box>
              </Box>
              <Box sx={{ mt: 0.5 }}>
                <CheckboxField
                  label={
                    <Typography variant="body2" sx={{ fontSize: "0.8rem" }}>
                      Zobrazit název v PDF
                    </Typography>
                  }
                  checked={field.showLabel !== false}
                  onChange={(checked) => {
                    const updated = [...customFields];
                    updated[idx] = {
                      ...updated[idx],
                      showLabel: checked,
                    };
                    setCustomFields(updated);
                  }}
                />
              </Box>
            </Box>
          ))}
          <Button
            variant="outlined"
            color="inherit"
            size="small"
            startIcon={SmallPlusIcon}
            onClick={() =>
              setCustomFields([
                ...customFields,
                {
                  name: "",
                  value: "",
                  showLabel: true,
                  _key: `cf-${++customFieldKeyCounter.current}`,
                },
              ])
            }
            sx={{ mt: 0.5 }}
          >
            Přidat pole
          </Button>
        </Box>

        {/* Field order for PDF */}
        <Box sx={{ mt: 2 }}>
          <Typography
            variant="body2"
            sx={{ fontWeight: 600, color: "text.secondary" }}
          >
            Pořadí polí v PDF
          </Typography>
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ display: "block", mb: 1 }}
          >
            Určuje pořadí řádků v adresním bloku zákazníka na PDF nabídce.
          </Typography>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 0.5 }}>
            {fullFieldOrder.map((key, index) => (
              <Box
                key={key}
                sx={{
                  display: "flex",
                  alignItems: "center",
                  gap: 1,
                  px: 1,
                  py: 0.5,
                  border: 1,
                  borderColor: "divider",
                  borderRadius: 1,
                }}
              >
                <Box sx={{ display: "flex", flexDirection: "column" }}>
                  <IconButton
                    size="small"
                    onClick={() => moveField(index, -1)}
                    disabled={index === 0}
                    title="Nahoru"
                    aria-label="Nahoru"
                    sx={{ p: 0.25 }}
                  >
                    {UpIcon}
                  </IconButton>
                  <IconButton
                    size="small"
                    onClick={() => moveField(index, 1)}
                    disabled={index === fullFieldOrder.length - 1}
                    title="Dolů"
                    aria-label="Dolů"
                    sx={{ p: 0.25 }}
                  >
                    {DownIcon}
                  </IconButton>
                </Box>
                <Typography
                  variant="body2"
                  sx={{
                    color: key.startsWith("custom_")
                      ? "primary.main"
                      : "text.primary",
                    fontWeight: key.startsWith("custom_") ? 600 : 400,
                  }}
                >
                  {getFieldDisplayName(key)}
                </Typography>
              </Box>
            ))}
          </Box>
        </Box>
      </Modal>

      {/* Delete Confirm Modal */}
      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, customer: null })}
        onConfirm={handleDelete}
        title="Smazat zákazníka"
        message={`Opravdu chcete smazat zákazníka "${deleteConfirm.customer?.name}"? Tato akce je nevratná.`}
        confirmText="Smazat"
        cancelText="Zrušit"
        confirmVariant="danger"
        loading={deleting}
      />
    </PageEnter>
  );
}
