import type { ReactNode } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import RichEditor from "../RichEditor";
import {
  Button,
  Card,
  TextField,
  Field,
  StatusChip,
  EmptyState,
} from "../../ui";

/** One bilingual rich-text PDF section (offers' scope ≡ issued orders' sections). */
export interface DocumentSection {
  title: string;
  title_cz: string;
  content: string;
}

export const emptyDocumentSection = (): DocumentSection => ({
  title: "",
  title_cz: "",
  content: "",
});

const RemoveIcon = (
  <svg
    width="16"
    height="16"
    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="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <polyline points="18 15 12 9 6 15" />
  </svg>
);

const DownIcon = (
  <svg
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <polyline points="6 9 12 15 18 9" />
  </svg>
);

interface SectionsEditorProps {
  sections: DocumentSection[];
  onChange: (sections: DocumentSection[]) => void;
  readOnly: boolean;
  /** Card heading. */
  title?: string;
  /**
   * Document language — "CZ"/"cs" prefers the Czech section title in the
   * "Sekce N — …" header line, anything else the English one.
   */
  language?: string;
  /** Optional page-specific control (e.g. scope-template Select) next to the add button. */
  templatesSlot?: ReactNode;
}

/**
 * Bilingual rich-text sections editor shared by the document detail pages
 * (lifted from OfferDetail's "Rozsah projektu" card): bordered section boxes
 * with EN/CZ title fields (StatusChip badges), Quill content, up/down
 * reorder and add/remove. Offers pass their template Select via
 * `templatesSlot`; issued orders don't (no templates on POs).
 */
export default function SectionsEditor({
  sections,
  onChange,
  readOnly,
  title = "Rozsah projektu",
  language,
  templatesSlot,
}: SectionsEditorProps) {
  const preferCz =
    (language ?? "").toLowerCase().startsWith("cs") ||
    (language ?? "").toUpperCase() === "CZ";

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

  const moveSection = (index: number, delta: -1 | 1) => {
    const target = index + delta;
    if (target < 0 || target >= sections.length) return;
    const arr = [...sections];
    [arr[index], arr[target]] = [arr[target], arr[index]];
    onChange(arr);
  };

  return (
    <Card sx={{ mb: 3 }}>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 2,
        }}
      >
        <Typography variant="subtitle2" sx={{ fontWeight: 600 }}>
          {title}
        </Typography>
        {!readOnly && (
          <Box sx={{ display: "flex", gap: 1, alignItems: "center" }}>
            {templatesSlot}
            <Button
              type="button"
              onClick={() => onChange([...sections, emptyDocumentSection()])}
              variant="outlined"
              color="inherit"
              size="small"
            >
              + Přidat sekci
            </Button>
          </Box>
        )}
      </Box>

      {sections.length === 0 ? (
        <EmptyState
          title={
            templatesSlot
              ? 'Žádné sekce rozsahu. Klikněte na "Přidat sekci" nebo vyberte šablonu.'
              : 'Žádné sekce rozsahu. Klikněte na "Přidat sekci".'
          }
        />
      ) : (
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: 3,
            mt: 1,
          }}
        >
          {sections.map((section, idx) => (
            <Box
              key={idx}
              sx={{
                border: 1,
                borderColor: "divider",
                borderRadius: 2,
                p: 2,
                bgcolor: "action.hover",
              }}
            >
              <Box
                sx={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  mb: 1.5,
                }}
              >
                <Typography
                  variant="body2"
                  sx={{ fontWeight: 600, color: "text.secondary" }}
                >
                  Sekce {idx + 1}
                  {(preferCz ? section.title_cz : section.title) && (
                    <Box component="span" sx={{ fontWeight: 400, ml: 1 }}>
                      —{" "}
                      {preferCz
                        ? section.title_cz || section.title
                        : section.title}
                    </Box>
                  )}
                </Typography>
                {!readOnly && (
                  <Box sx={{ display: "flex", gap: 0.25 }}>
                    {idx > 0 && (
                      <IconButton
                        size="small"
                        onClick={() => moveSection(idx, -1)}
                        title="Posunout nahoru"
                        aria-label="Posunout nahoru"
                      >
                        {UpIcon}
                      </IconButton>
                    )}
                    {idx < sections.length - 1 && (
                      <IconButton
                        size="small"
                        onClick={() => moveSection(idx, 1)}
                        title="Posunout dolů"
                        aria-label="Posunout dolů"
                      >
                        {DownIcon}
                      </IconButton>
                    )}
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() =>
                        onChange(sections.filter((_, i) => i !== idx))
                      }
                      title="Odebrat sekci"
                      aria-label="Odebrat sekci"
                    >
                      {RemoveIcon}
                    </IconButton>
                  </Box>
                )}
              </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(idx, "title", e.target.value)
                    }
                    placeholder="Název sekce (anglicky)"
                    InputProps={{ readOnly }}
                    slotProps={{ htmlInput: { maxLength: 500 } }}
                  />
                </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(idx, "title_cz", e.target.value)
                    }
                    placeholder="Název sekce (česky)"
                    InputProps={{ readOnly }}
                    slotProps={{ htmlInput: { maxLength: 500 } }}
                  />
                </Box>
              </Box>

              <Field label="Obsah">
                <RichEditor
                  value={section.content}
                  onChange={(val) => updateSection(idx, "content", val)}
                  placeholder="Obsah sekce..."
                  minHeight="120px"
                  readOnly={readOnly}
                />
              </Field>
            </Box>
          ))}
        </Box>
      )}
    </Card>
  );
}
