import { useState, 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 RichEditor from "../components/RichEditor";
import {
  itemTemplatesOptions,
  scopeTemplatesOptions,
  type ItemTemplate,
  type ScopeTemplate,
  type ScopeSection,
} from "../lib/queries/offers";
import { useApiMutation } from "../lib/queries/mutations";
import apiFetch from "../utils/api";
import {
  Button,
  Card,
  DataTable,
  Modal,
  ConfirmDialog,
  Field,
  TextField,
  StatusChip,
  PageHeader,
  PageEnter,
  EmptyState,
  LoadingState,
  Tabs,
  TabPanel,
  type DataColumn,
  type TabDef,
} from "../ui";

const API_BASE = "/api/admin";

interface ItemForm {
  name: string;
  description: string;
  default_price: number;
  category: string;
}

interface ScopeForm {
  name: string;
  sections: ScopeSection[];
}

const PlusIcon = (
  <svg
    width="16"
    height="16"
    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 UpIcon = (
  <svg
    width="14"
    height="14"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M18 15l-6-6-6 6" />
  </svg>
);
const DownIcon = (
  <svg
    width="14"
    height="14"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <path d="M6 9l6 6 6-6" />
  </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>
);

export default function OffersTemplates() {
  const { hasPermission } = useAuth();
  const [activeTab, setActiveTab] = useState<"items" | "scopes">("items");

  if (!hasPermission("settings.templates")) return <Forbidden />;

  const tabs: TabDef[] = [
    { value: "items", label: "Šablony položek" },
    { value: "scopes", label: "Šablony rozsahu" },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Šablony"
        subtitle="Šablony položek a rozsahu projektu"
      />

      <Tabs
        value={activeTab}
        onChange={(v) => setActiveTab(v as "items" | "scopes")}
        tabs={tabs}
      />

      <TabPanel value="items" current={activeTab}>
        <ItemTemplatesTab />
      </TabPanel>
      <TabPanel value="scopes" current={activeTab}>
        <ScopeTemplatesTab />
      </TabPanel>
    </PageEnter>
  );
}

// --- Item Templates Tab ---

function ItemTemplatesTab() {
  const alert = useAlert();
  const { data: templates = [], isPending } = useQuery(itemTemplatesOptions());
  const [showModal, setShowModal] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<ItemTemplate | null>(
    null,
  );
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<ItemForm>({
    name: "",
    description: "",
    default_price: 0,
    category: "",
  });
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    template: ItemTemplate | null;
  }>({ show: false, template: null });
  const [deleting, setDeleting] = useState(false);

  const submitMutation = useApiMutation<
    ItemForm & { id?: number },
    { message?: string; error?: string }
  >({
    url: () => `${API_BASE}/offers-templates?action=item`,
    method: () => "POST",
    invalidate: ["offer-templates", "offers"],
    onSuccess: (data) => {
      setShowModal(false);
      setTimeout(() => alert.success(data?.message || "Uloženo"), 300);
    },
  });

  const deleteMutation = useApiMutation<
    number,
    { message?: string; error?: string }
  >({
    url: (id) => `${API_BASE}/offers-templates?action=item&id=${id}`,
    method: () => "DELETE",
    invalidate: ["offer-templates", "offers"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, template: null });
      alert.success(data?.message || "Smazáno");
    },
  });

  const openCreate = () => {
    setEditingTemplate(null);
    setForm({ name: "", description: "", default_price: 0, category: "" });
    setShowModal(true);
  };

  const openEdit = (t: ItemTemplate) => {
    setEditingTemplate(t);
    setForm({
      name: t.name || "",
      description: t.description || "",
      default_price: t.default_price || 0,
      category: t.category || "",
    });
    setShowModal(true);
  };

  const handleSubmit = async () => {
    if (!form.name.trim()) {
      alert.error("Název šablony je povinný");
      return;
    }
    const body = editingTemplate ? { ...form, id: editingTemplate.id } : form;
    setSaving(true);
    try {
      await submitMutation.mutateAsync(body);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.template) return;
    setDeleting(true);
    try {
      await deleteMutation.mutateAsync(deleteConfirm.template.id);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setDeleting(false);
    }
  };

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

  const columns: DataColumn<ItemTemplate>[] = [
    {
      key: "name",
      header: "Název",
      width: "26%",
      bold: true,
      render: (t) => t.name,
    },
    {
      key: "description",
      header: "Popis",
      width: "30%",
      render: (t) => (
        <Box component="span" sx={{ color: "text.secondary" }}>
          {t.description || "—"}
        </Box>
      ),
    },
    {
      key: "default_price",
      header: "Cena",
      width: "14%",
      mono: true,
      render: (t) => Number(t.default_price).toFixed(2),
    },
    {
      key: "category",
      header: "Kategorie",
      width: "18%",
      render: (t) => (
        <Box component="span" sx={{ color: "text.secondary" }}>
          {t.category || "—"}
        </Box>
      ),
    },
    {
      key: "actions",
      header: "Akce",
      width: "12%",
      align: "right",
      render: (t) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => openEdit(t)}
            aria-label="Upravit"
            title="Upravit"
          >
            {EditIcon}
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => setDeleteConfirm({ show: true, template: t })}
            aria-label="Smazat"
            title="Smazat"
          >
            {DeleteIcon}
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <Box>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 2,
        }}
      >
        <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
          Šablony položek ({templates.length})
        </Typography>
        <Button size="small" startIcon={PlusIcon} onClick={openCreate}>
          Přidat
        </Button>
      </Box>

      <Card>
        <DataTable<ItemTemplate>
          columns={columns}
          rows={templates}
          rowKey={(t) => t.id}
          empty={<EmptyState title="Zatím žádné šablony položek." />}
        />
      </Card>

      {/* Item Template Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={editingTemplate ? "Upravit šablonu" : "Nová šablona položky"}
        submitText={editingTemplate ? "Uložit" : "Vytvořit"}
        loading={saving}
        maxWidth="md"
      >
        <Field label="Název" required>
          <TextField
            value={form.name}
            onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
          />
        </Field>
        <Field label="Popis">
          <TextField
            value={form.description}
            onChange={(e) =>
              setForm((p) => ({ ...p, description: e.target.value }))
            }
            multiline
            rows={2}
          />
        </Field>
        <Box
          sx={{
            display: "grid",
            gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
            gap: 2,
          }}
        >
          <Field label="Výchozí cena">
            <TextField
              type="number"
              value={form.default_price}
              onChange={(e) =>
                setForm((p) => ({
                  ...p,
                  default_price: parseFloat(e.target.value),
                }))
              }
              slotProps={{ htmlInput: { step: "0.01", inputMode: "decimal" } }}
            />
          </Field>
          <Field label="Kategorie">
            <TextField
              value={form.category}
              onChange={(e) =>
                setForm((p) => ({ ...p, category: e.target.value }))
              }
            />
          </Field>
        </Box>
      </Modal>

      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, template: null })}
        onConfirm={handleDelete}
        title="Smazat šablonu"
        message={`Opravdu chcete smazat šablonu "${deleteConfirm.template?.name}"?`}
        confirmText="Smazat"
        cancelText="Zrušit"
        confirmVariant="danger"
        loading={deleting}
      />
    </Box>
  );
}

// --- Scope Templates Tab ---

function ScopeTemplatesTab() {
  const alert = useAlert();
  const { data: templates = [], isPending } = useQuery(scopeTemplatesOptions());
  const [showModal, setShowModal] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<ScopeTemplate | null>(
    null,
  );
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<ScopeForm>({ name: "", sections: [] });
  const sectionKeyCounter = useRef(0);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    template: ScopeTemplate | null;
  }>({ show: false, template: null });
  const [deleting, setDeleting] = useState(false);

  const submitMutation = useApiMutation<
    ScopeForm,
    { message?: string; error?: string }
  >({
    url: () =>
      editingTemplate
        ? `${API_BASE}/offers-templates/${editingTemplate.id}`
        : `${API_BASE}/offers-templates`,
    method: () => (editingTemplate ? "PUT" : "POST"),
    invalidate: ["offer-templates", "offers"],
    onSuccess: (data) => {
      setShowModal(false);
      setTimeout(() => alert.success(data?.message || "Uloženo"), 300);
    },
  });

  const deleteMutation = useApiMutation<
    number,
    { message?: string; error?: string }
  >({
    url: (id) => `${API_BASE}/offers-templates/${id}`,
    method: () => "DELETE",
    invalidate: ["offer-templates", "offers"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, template: null });
      alert.success(data?.message || "Smazáno");
    },
  });

  const openCreate = () => {
    setEditingTemplate(null);
    setForm({
      name: "",
      sections: [
        {
          _key: `sc-${++sectionKeyCounter.current}`,
          title: "",
          title_cz: "",
          content: "",
        },
      ],
    });
    setShowModal(true);
  };

  const openEdit = async (t: ScopeTemplate) => {
    try {
      const response = await apiFetch(`${API_BASE}/offers-templates/${t.id}`);
      const result = await response.json();
      if (result.success) {
        setEditingTemplate(result.data);
        const templateSections =
          result.data.scope_template_sections || result.data.sections || [];
        setForm({
          name: result.data.name || "",
          sections: templateSections.length
            ? templateSections.map(
                (s: {
                  title?: string;
                  title_cz?: string;
                  content?: string;
                }) => ({
                  _key: `sc-${++sectionKeyCounter.current}`,
                  title: s.title || "",
                  title_cz: s.title_cz || "",
                  content: s.content || "",
                }),
              )
            : [
                {
                  _key: `sc-${++sectionKeyCounter.current}`,
                  title: "",
                  title_cz: "",
                  content: "",
                },
              ],
        });
        setShowModal(true);
      }
    } catch {
      alert.error("Nepodařilo se načíst detail šablony");
    }
  };

  const addSection = () => {
    setForm((prev) => ({
      ...prev,
      sections: [
        ...prev.sections,
        {
          _key: `sc-${++sectionKeyCounter.current}`,
          title: "",
          title_cz: "",
          content: "",
        },
      ],
    }));
  };

  const removeSection = (index: number) => {
    setForm((prev) => ({
      ...prev,
      sections: prev.sections.filter((_, i) => i !== index),
    }));
  };

  const updateSection = (index: number, field: string, value: string) => {
    setForm((prev) => ({
      ...prev,
      sections: prev.sections.map((s, i) =>
        i === index ? { ...s, [field]: value } : s,
      ),
    }));
  };

  const moveSection = (index: number, direction: number) => {
    setForm((prev) => {
      const newSections = [...prev.sections];
      const targetIndex = index + direction;
      if (targetIndex < 0 || targetIndex >= newSections.length) return prev;
      [newSections[index], newSections[targetIndex]] = [
        newSections[targetIndex],
        newSections[index],
      ];
      return { ...prev, sections: newSections };
    });
  };

  const handleSubmit = async () => {
    if (!form.name.trim()) {
      alert.error("Název šablony je povinný");
      return;
    }
    setSaving(true);
    try {
      await submitMutation.mutateAsync(form);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.template) return;
    setDeleting(true);
    try {
      await deleteMutation.mutateAsync(deleteConfirm.template.id);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    } finally {
      setDeleting(false);
    }
  };

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

  const columns: DataColumn<ScopeTemplate>[] = [
    {
      key: "name",
      header: "Název",
      width: "80%",
      bold: true,
      render: (t) => t.name,
    },
    {
      key: "actions",
      header: "Akce",
      width: "20%",
      align: "right",
      render: (t) => (
        <Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
          <IconButton
            size="small"
            onClick={() => openEdit(t)}
            aria-label="Upravit"
            title="Upravit"
          >
            {EditIcon}
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => setDeleteConfirm({ show: true, template: t })}
            aria-label="Smazat"
            title="Smazat"
          >
            {DeleteIcon}
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <Box>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 2,
        }}
      >
        <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
          Šablony rozsahu ({templates.length})
        </Typography>
        <Button size="small" startIcon={PlusIcon} onClick={openCreate}>
          Přidat
        </Button>
      </Box>

      <Card>
        <DataTable<ScopeTemplate>
          columns={columns}
          rows={templates}
          rowKey={(t) => t.id}
          empty={<EmptyState title="Zatím žádné šablony rozsahu." />}
        />
      </Card>

      {/* Scope Template Modal (large) */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSubmit={handleSubmit}
        title={
          editingTemplate ? "Upravit šablonu rozsahu" : "Nová šablona rozsahu"
        }
        submitText={editingTemplate ? "Uložit" : "Vytvořit"}
        maxWidth="lg"
        loading={saving}
      >
        <Field label="Název šablony" required>
          <TextField
            value={form.name}
            onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
          />
        </Field>

        <Box>
          <Typography
            component="label"
            variant="body2"
            sx={{
              display: "block",
              mb: 1,
              fontWeight: 600,
              color: "text.secondary",
            }}
          >
            Sekce
          </Typography>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
            {form.sections.map((section, index) => (
              <Box
                key={section._key}
                sx={{
                  border: 1,
                  borderColor: "divider",
                  borderRadius: 2,
                  p: 2,
                }}
              >
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                    mb: 1.5,
                  }}
                >
                  <Typography
                    variant="body2"
                    sx={{ fontWeight: 700, color: "text.secondary" }}
                  >
                    {index + 1}.
                  </Typography>
                  <Typography
                    variant="body2"
                    sx={{ fontWeight: 600, flex: 1 }}
                    noWrap
                  >
                    {section.title || section.title_cz || `Sekce ${index + 1}`}
                  </Typography>
                  <IconButton
                    size="small"
                    onClick={() => moveSection(index, -1)}
                    disabled={index === 0}
                    title="Posunout nahoru"
                    aria-label="Posunout nahoru"
                  >
                    {UpIcon}
                  </IconButton>
                  <IconButton
                    size="small"
                    onClick={() => moveSection(index, 1)}
                    disabled={index === form.sections.length - 1}
                    title="Posunout dolů"
                    aria-label="Posunout dolů"
                  >
                    {DownIcon}
                  </IconButton>
                  {form.sections.length > 1 && (
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => removeSection(index)}
                      title="Odebrat"
                      aria-label="Odebrat"
                    >
                      {RemoveIcon}
                    </IconButton>
                  )}
                </Box>

                <Box
                  sx={{
                    display: "grid",
                    gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" },
                    gap: 2,
                  }}
                >
                  <Box sx={{ mb: 2 }}>
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 0.75,
                        mb: 0.5,
                      }}
                    >
                      <StatusChip label="EN" color="info" />
                      <Typography
                        component="label"
                        variant="body2"
                        sx={{ fontWeight: 600, color: "text.secondary" }}
                      >
                        Název sekce
                      </Typography>
                    </Box>
                    <TextField
                      value={section.title}
                      onChange={(e) =>
                        updateSection(index, "title", e.target.value)
                      }
                      placeholder="Název sekce (anglicky)"
                    />
                  </Box>
                  <Box sx={{ mb: 2 }}>
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 0.75,
                        mb: 0.5,
                      }}
                    >
                      <StatusChip label="CZ" color="success" />
                      <Typography
                        component="label"
                        variant="body2"
                        sx={{ fontWeight: 600, color: "text.secondary" }}
                      >
                        Název sekce
                      </Typography>
                    </Box>
                    <TextField
                      value={section.title_cz}
                      onChange={(e) =>
                        updateSection(index, "title_cz", e.target.value)
                      }
                      placeholder="Název sekce (česky)"
                    />
                  </Box>
                </Box>

                <Field label="Obsah">
                  <RichEditor
                    value={section.content}
                    onChange={(val) => updateSection(index, "content", val)}
                    placeholder="Obsah sekce..."
                    minHeight="150px"
                  />
                </Field>
              </Box>
            ))}
          </Box>
          <Box sx={{ mt: 1.5 }}>
            <Button
              variant="outlined"
              color="inherit"
              size="small"
              startIcon={PlusIcon}
              onClick={addSection}
            >
              Přidat sekci
            </Button>
          </Box>
        </Box>
      </Modal>

      <ConfirmDialog
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, template: null })}
        onConfirm={handleDelete}
        title="Smazat šablonu"
        message={`Opravdu chcete smazat šablonu "${deleteConfirm.template?.name}"?`}
        confirmText="Smazat"
        cancelText="Zrušit"
        confirmVariant="danger"
        loading={deleting}
      />
    </Box>
  );
}
