import { useState, useCallback } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { Modal, Button, TextField, Field } from "../ui";
import { useAlert } from "../context/AlertContext";

interface ConfirmationItem {
  description: string;
  quantity: number;
  unit: string;
  unit_price: number;
  is_included_in_total: boolean;
  vat_rate: number;
}

interface OrderConfirmationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onGenerate: (
    lang: string,
    applyVat: boolean,
    items?: ConfirmationItem[],
  ) => Promise<void>;
  initialItems: ConfirmationItem[];
  orderNumber: string;
  defaultVatRate: number;
  applyVat: boolean;
}

export default function OrderConfirmationModal({
  isOpen,
  onClose,
  onGenerate,
  initialItems,
  orderNumber,
  defaultVatRate,
  applyVat,
}: OrderConfirmationModalProps) {
  const alert = useAlert();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [step, setStep] = useState<"choose" | "edit">("choose");
  const [lang, setLang] = useState<string>("cs");
  const [applyVatState, setApplyVatState] = useState(applyVat);
  const [items, setItems] = useState<ConfirmationItem[]>(initialItems);
  const [loading, setLoading] = useState(false);

  const handleUseExisting = async () => {
    setLoading(true);
    try {
      await onGenerate(lang, applyVatState, undefined);
    } catch (err) {
      console.error("Chyba při generování potvrzení:", err);
      alert.error("Nepodařilo se vygenerovat potvrzení");
    } finally {
      setLoading(false);
      setStep("choose");
      onClose();
    }
  };

  const handleEditGenerate = async () => {
    setLoading(true);
    try {
      await onGenerate(lang, applyVatState, items);
    } catch (err) {
      console.error("Chyba při generování potvrzení:", err);
      alert.error("Nepodařilo se vygenerovat potvrzení");
    } finally {
      setLoading(false);
      setStep("choose");
      onClose();
    }
  };

  const updateItem = useCallback(
    (
      index: number,
      field: keyof ConfirmationItem,
      value: string | number | boolean,
    ) => {
      setItems((prev) => {
        const next = [...prev];
        next[index] = { ...next[index], [field]: value };
        return next;
      });
    },
    [],
  );

  const removeItem = useCallback((index: number) => {
    setItems((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const addItem = useCallback(() => {
    setItems((prev) => [
      ...prev,
      {
        description: "",
        quantity: 1,
        unit: "ks",
        unit_price: 0,
        is_included_in_total: true,
        vat_rate: defaultVatRate,
      },
    ]);
  }, [defaultVatRate]);

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={`Potvrzení objednávky ${orderNumber}`}
      maxWidth={step === "edit" ? "lg" : "md"}
      loading={loading}
      submitText={
        step === "choose" ? "Použít položky z objednávky" : "Vygenerovat PDF"
      }
      submitDisabled={step === "edit" && items.length === 0}
      onSubmit={step === "choose" ? handleUseExisting : handleEditGenerate}
    >
      {step === "choose" ? (
        <Box>
          <Field label="Jazyk dokumentu">
            <Box sx={{ display: "flex", gap: 1 }}>
              <Button
                size="small"
                variant={lang === "cs" ? "contained" : "outlined"}
                color={lang === "cs" ? "primary" : "inherit"}
                onClick={() => setLang("cs")}
              >
                Čeština
              </Button>
              <Button
                size="small"
                variant={lang === "en" ? "contained" : "outlined"}
                color={lang === "en" ? "primary" : "inherit"}
                onClick={() => setLang("en")}
              >
                English
              </Button>
            </Box>
          </Field>

          <Field label="DPH">
            <Box sx={{ display: "flex", gap: 1 }}>
              <Button
                size="small"
                variant={applyVatState ? "contained" : "outlined"}
                color={applyVatState ? "primary" : "inherit"}
                onClick={() => setApplyVatState(true)}
              >
                S DPH
              </Button>
              <Button
                size="small"
                variant={!applyVatState ? "contained" : "outlined"}
                color={!applyVatState ? "primary" : "inherit"}
                onClick={() => setApplyVatState(false)}
              >
                Bez DPH
              </Button>
            </Box>
          </Field>

          <Field label="Obsah potvrzení">
            <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
              Jak chcete připravit potvrzení objednávky?
            </Typography>
            <Button
              fullWidth
              onClick={() => {
                setItems(initialItems.length > 0 ? initialItems : []);
                setStep("edit");
              }}
              disabled={loading}
              variant="outlined"
              color="inherit"
            >
              Upravit položky
            </Button>
          </Field>
        </Box>
      ) : (
        <Box>
          <Box sx={{ mb: 1.5 }}>
            <Button
              size="small"
              variant="outlined"
              color="inherit"
              onClick={() => setStep("choose")}
              disabled={loading}
            >
              Zpět
            </Button>
          </Box>
          {isMobile ? (
            <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
              {items.map((item, i) => (
                <Box
                  key={i}
                  sx={{
                    border: 1,
                    borderColor: "divider",
                    borderRadius: 2,
                    p: 1.5,
                    display: "flex",
                    flexDirection: "column",
                    gap: 1,
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                    <Typography
                      variant="caption"
                      sx={{ color: "text.secondary", fontWeight: 700 }}
                    >
                      Položka {i + 1}
                    </Typography>
                    <Box sx={{ flex: 1 }} />
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => removeItem(i)}
                      title="Odstranit"
                      aria-label="Odstranit"
                    >
                      <svg
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      >
                        <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>
                    </IconButton>
                  </Box>
                  <TextField
                    label="Popis"
                    value={item.description}
                    onChange={(e) =>
                      updateItem(i, "description", e.target.value)
                    }
                  />
                  <Box
                    sx={{
                      display: "grid",
                      gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
                      gap: 1,
                    }}
                  >
                    <TextField
                      label="Množství"
                      type="number"
                      value={item.quantity}
                      onChange={(e) =>
                        updateItem(i, "quantity", Number(e.target.value) || 0)
                      }
                      slotProps={{ htmlInput: { step: "0.001" } }}
                    />
                    <TextField
                      label="Jednotka"
                      value={item.unit}
                      onChange={(e) => updateItem(i, "unit", e.target.value)}
                    />
                    <TextField
                      label="Cena"
                      type="number"
                      value={item.unit_price}
                      onChange={(e) =>
                        updateItem(i, "unit_price", Number(e.target.value) || 0)
                      }
                      slotProps={{ htmlInput: { step: "0.01" } }}
                    />
                    <TextField
                      label="%DPH"
                      type="number"
                      value={item.vat_rate}
                      onChange={(e) =>
                        updateItem(i, "vat_rate", Number(e.target.value) || 0)
                      }
                      slotProps={{ htmlInput: { step: "1" } }}
                    />
                  </Box>
                </Box>
              ))}
            </Box>
          ) : (
            <Box sx={{ overflowX: "auto" }}>
              <Box
                component="table"
                sx={{
                  width: "100%",
                  borderCollapse: "collapse",
                  "& th": {
                    textAlign: "left",
                    fontSize: ".7rem",
                    textTransform: "uppercase",
                    letterSpacing: ".05em",
                    fontWeight: 700,
                    color: "text.secondary",
                    pb: 1,
                  },
                  "& td": { py: 0.5, pr: 1, verticalAlign: "middle" },
                }}
              >
                <thead>
                  <tr>
                    <th>Popis</th>
                    <th>Mn.</th>
                    <th>Jedn.</th>
                    <th>Cena</th>
                    <th>%DPH</th>
                    <th style={{ width: "40px" }} />
                  </tr>
                </thead>
                <tbody>
                  {items.map((item, i) => (
                    <tr key={i}>
                      <td>
                        <TextField
                          value={item.description}
                          onChange={(e) =>
                            updateItem(i, "description", e.target.value)
                          }
                          sx={{ minWidth: 200 }}
                        />
                      </td>
                      <td>
                        <TextField
                          type="number"
                          value={item.quantity}
                          onChange={(e) =>
                            updateItem(
                              i,
                              "quantity",
                              Number(e.target.value) || 0,
                            )
                          }
                          sx={{ width: 90 }}
                          slotProps={{ htmlInput: { step: "0.001" } }}
                        />
                      </td>
                      <td>
                        <TextField
                          value={item.unit}
                          onChange={(e) =>
                            updateItem(i, "unit", e.target.value)
                          }
                          sx={{ width: 70 }}
                        />
                      </td>
                      <td>
                        <TextField
                          type="number"
                          value={item.unit_price}
                          onChange={(e) =>
                            updateItem(
                              i,
                              "unit_price",
                              Number(e.target.value) || 0,
                            )
                          }
                          sx={{ width: 110 }}
                          slotProps={{ htmlInput: { step: "0.01" } }}
                        />
                      </td>
                      <td>
                        <TextField
                          type="number"
                          value={item.vat_rate}
                          onChange={(e) =>
                            updateItem(
                              i,
                              "vat_rate",
                              Number(e.target.value) || 0,
                            )
                          }
                          sx={{ width: 80 }}
                          slotProps={{ htmlInput: { step: "1" } }}
                        />
                      </td>
                      <td>
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => removeItem(i)}
                          title="Odstranit"
                          aria-label="Odstranit"
                        >
                          <svg
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                          >
                            <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>
                        </IconButton>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </Box>
            </Box>
          )}
          <Box sx={{ mt: 1.5 }}>
            <Button
              size="small"
              variant="outlined"
              color="inherit"
              onClick={addItem}
            >
              + Přidat položku
            </Button>
          </Box>
        </Box>
      )}
    </Modal>
  );
}
