import {
  TextField,
  FormControlLabel,
  Checkbox,
  Button,
  Alert,
  CircularProgress,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { submitFormData } from "../utils/sender";

interface Message {
  type: "error" | "info" | "success" | "warning";
  headline: string;
  text: string;
}

export const MainForm = () => {
  const { t } = useTranslation();
  const [invoice, setInvoice] = useState(false);
  const [msg, setMsg] = useState<Message | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phoneNumber: "",
    tickets: 1,
    companyName: "",
    cmpFirstName: "",
    cpmLastName: "",
    cpmEmail: "",
    cpmPhoneNumber: "",
    street: "",
    postalCode: "",
    paymentMethod: "",
    code: "",
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async () => {
    setIsLoading(true);
    try {
      const result = await submitFormData(formData);
      if (result.success) {
        setMsg({
          type: "success",
          headline: t("success"),
          text: t("form-submitted-successfully"),
        });
      } else {
        setMsg({
          type: "error",
          headline: t("error"),
          text: result.error || t("form-submission-failed"),
        });
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          handleSubmit();
        }}
      >
        <TextField
          required
          id="first-name"
          label={t("first-name")}
          variant="filled"
          value={formData.firstName}
          onChange={handleChange}
          name="firstName"
        />
        <TextField
          required
          id="last-name"
          label={t("last-name")}
          variant="filled"
          value={formData.lastName}
          onChange={handleChange}
          name="lastName"
        />
        <TextField
          required
          id="email"
          label={t("email")}
          variant="filled"
          type="email"
          value={formData.email}
          onChange={handleChange}
          name="email"
        />
        <TextField
          required
          id="phone-number"
          label={t("phone-number")}
          variant="filled"
          type="tel"
          value={formData.phoneNumber}
          onChange={handleChange}
          name="phoneNumber"
        />
        <TextField
          required
          id="tickets"
          type="number"
          label={t("tickets")}
          variant="filled"
          value={formData.tickets}
          onChange={handleChange}
          name="tickets"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={invoice}
              onChange={(e) => setInvoice(e.target.checked)}
            />
          }
          label={t("invoice")}
        />
        {invoice && (
          <>
            <TextField
              required
              id="company-name"
              label={t("company-name")}
              variant="filled"
              value={formData.companyName}
              onChange={handleChange}
              name="companyName"
            />
            <TextField
              required
              id="first-name_invoice"
              label={t("first-name")}
              variant="filled"
              value={formData.cmpFirstName}
              onChange={handleChange}
              name="cmpFirstName"
            />
            <TextField
              required
              id="last-name_invoice"
              label={t("last-name")}
              variant="filled"
              value={formData.cpmLastName}
              onChange={handleChange}
              name="cpmLastName"
            />
            <TextField
              required
              id="street"
              label={t("street")}
              variant="filled"
              value={formData.street}
              onChange={handleChange}
              name="street"
            />
            <TextField
              required
              id="postal-code"
              label={t("postal-code")}
              variant="filled"
              value={formData.postalCode}
              onChange={handleChange}
              name="postalCode"
            />
            <TextField
              required
              id="phone-number_invoice"
              label={t("phone-number")}
              variant="filled"
              type="tel"
              value={formData.cpmPhoneNumber}
              onChange={handleChange}
              name="cpmPhoneNumber"
            />
            <TextField
              required
              id="email_invoice"
              label={t("email")}
              variant="filled"
              type="email"
              value={formData.cpmEmail}
              onChange={handleChange}
              name="cpmEmail"
            />
          </>
        )}
        {/* Payment methods - only one must be selected */}
        <FormControlLabel control={<Checkbox />} label={t("cash")} />
        <FormControlLabel control={<Checkbox />} label={t("paypal")} />
        <FormControlLabel control={<Checkbox />} label={t("transfer")} />
        <TextField required id="code" label={t("code")} variant="filled" />
        {isLoading && <CircularProgress />}
        <button type="submit">
          <Button
            onClick={() => {
              handleSubmit();
            }}
            variant="contained"
          >
            {t("submit")}
          </Button>
        </button>

        {msg && (
          <Alert severity={msg.type}>
            {msg.headline}: {msg.text}
          </Alert>
        )}
      </form>
    </>
  );
};
