import {
  Button,
  Paper,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
} from "@mui/material";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Loader2, Save } from "lucide-react";

import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import {
  carrierStore,
  cityStore,
  authStore,
  mediaStore,
  languageStore,
  isMediaIdEmpty,
  useSelectedCity,
  selectedCityStore,
  SelectMediaDialog,
  UploadMediaDialog,
  PreviewMediaDialog,
} from "@shared";
import { useState, useEffect } from "react";
import { ImageUploadCard, LanguageSwitcher } from "@widgets";

type ColorFields = { main_color: string; left_color: string; right_color: string };

const colorFields = (data: ColorFields) => ({
  main_color: data.main_color,
  left_color: data.left_color,
  right_color: data.right_color,
});

const ColorPickerField = ({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (val: string) => void;
}) => (
  <div className="flex items-center gap-3 w-full">
    <div
      className="w-10 h-10 rounded border border-gray-300 flex-shrink-0 cursor-pointer overflow-hidden relative"
      style={{ backgroundColor: value || "#ffffff" }}
    >
      <input
        type="color"
        value={value || "#ffffff"}
        onChange={(e) => onChange(e.target.value)}
        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
      />
    </div>
    <TextField
      fullWidth
      label={label}
      value={value}
      placeholder="#000000"
      onChange={(e) => onChange(e.target.value)}
      InputProps={{
        endAdornment: value ? (
          <button
            type="button"
            onClick={() => onChange("")}
            className="text-gray-400 hover:text-gray-600 text-xs px-1"
          >
            ✕
          </button>
        ) : undefined,
      }}
    />
  </div>
);

export const CarrierCreatePage = observer(() => {
  const navigate = useNavigate();
  const { createCarrierData, setCreateCarrierData } = carrierStore;
  const { language } = languageStore;
  const canReadCities = authStore.canRead("cities");
  const { selectedCityId, selectedCity } = useSelectedCity();
  const [selectedMediaId, setSelectedMediaId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isSelectMediaOpen, setIsSelectMediaOpen] = useState(false);
  const [isUploadMediaOpen, setIsUploadMediaOpen] = useState(false);
  const [isPreviewMediaOpen, setIsPreviewMediaOpen] = useState(false);
  const [mediaId, setMediaId] = useState("");
  const [activeMenuType, setActiveMenuType] = useState<
    "thumbnail" | "watermark_lu" | "watermark_rd" | "image" | null
  >(null);

  useEffect(() => {
    selectedCityStore.setIsLocked(true);
    return () => selectedCityStore.setIsLocked(false);
  }, []);

  useEffect(() => {
    const fetchCities = async () => {
      if (!authStore.me) {
        await authStore.getMeAction().catch(() => undefined);
      }
      if (authStore.canRead("cities")) {
        await cityStore.getCities("ru");
        return;
      }
      await authStore.fetchMeCities().catch(() => undefined);
    };

    fetchCities();
    mediaStore.getMedia();
    languageStore.setLanguage("ru");
  }, []);

  const baseCities = canReadCities
    ? cityStore.cities["ru"].data
    : authStore.meCities["ru"].map((city) => ({
        id: city.city_id,
        name: city.name,
        country: "",
        country_code: "",
        arms: "",
      }));

  const availableCities =
    selectedCity?.id && !baseCities.some((city) => city.id === selectedCity.id)
      ? [selectedCity, ...baseCities]
      : baseCities;

  useEffect(() => {
    if (selectedCityId && !createCarrierData.city_id) {
      setCreateCarrierData(
        createCarrierData[language].full_name,
        createCarrierData[language].short_name,
        selectedCityId,
        createCarrierData[language].slogan,
        selectedMediaId || "",
        language,
      );
    }
  }, [selectedCityId, createCarrierData.city_id]);

  const handleCreate = async () => {
    try {
      setIsLoading(true);
      await carrierStore.createCarrier();

      toast.success("Перевозчик успешно создан");
      navigate("/carrier");
    } catch (error) {
      toast.error("Ошибка при создании перевозчика");
    } finally {
      setIsLoading(false);
    }
  };

  const handleMediaSelect = (media: {
    id: string;
    filename: string;
    media_name?: string;
    media_type: number;
  }) => {
    setSelectedMediaId(media.id);
    setCreateCarrierData(
      createCarrierData[language].full_name,
      createCarrierData[language].short_name,
      createCarrierData.city_id,
      createCarrierData[language].slogan,
      media.id,
      language,
    );
  };

  const selectedMedia =
    selectedMediaId && !isMediaIdEmpty(selectedMediaId)
      ? mediaStore.media.find((m) => m.id === selectedMediaId)
      : null;
  const effectiveLogoUrl = isMediaIdEmpty(selectedMediaId)
    ? null
    : selectedMedia?.id ?? selectedMediaId ?? null;

  return (
    <Paper className="w-full h-full p-3 flex flex-col gap-10">
      <LanguageSwitcher />
      <div className="flex items-center gap-4">
        <button
          className="flex items-center gap-2"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft size={20} />
          Назад
        </button>
      </div>

      <div className="flex flex-col gap-10 w-full items-end">
        <div className="flex gap-10 items-center mb-5 max-w-[80%] self-start">
          <h1 className="text-3xl break-words">Создание перевозчика</h1>
        </div>

        <FormControl fullWidth>
          <InputLabel>Город</InputLabel>
          <Select
            value={createCarrierData.city_id || ""}
            label="Город"
            required
            onChange={(e) =>
              setCreateCarrierData(
                createCarrierData[language].full_name,
                createCarrierData[language].short_name,
                e.target.value as number,
                createCarrierData[language].slogan,
                selectedMediaId || "",
                language,
              )
            }
          >
            {availableCities.map((city) => (
              <MenuItem key={city.id} value={city.id}>
                {city.name}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField
          fullWidth
          label="Полное название"
          value={createCarrierData[language].full_name}
          required
          onChange={(e) =>
            setCreateCarrierData(
              e.target.value,
              createCarrierData[language].short_name,
              createCarrierData.city_id,
              createCarrierData[language].slogan,
              selectedMediaId || "",
              language,
            )
          }
        />

        <TextField
          fullWidth
          label="Короткое название"
          value={createCarrierData[language].short_name}
          required
          onChange={(e) =>
            setCreateCarrierData(
              createCarrierData[language].full_name,
              e.target.value,
              createCarrierData.city_id,
              createCarrierData[language].slogan,
              selectedMediaId || "",
              language,
            )
          }
        />

        <TextField
          fullWidth
          label="Слоган"
          value={createCarrierData[language].slogan}
          onChange={(e) =>
            setCreateCarrierData(
              createCarrierData[language].full_name,
              createCarrierData[language].short_name,
              createCarrierData.city_id,
              e.target.value,
              selectedMediaId || "",
              language,
            )
          }
        />

        <div className="w-full flex flex-col gap-6">
          <div className="flex flex-col gap-1">
            <ColorPickerField
              label="Основной цвет"
              value={createCarrierData.main_color}
              onChange={(val) =>
                setCreateCarrierData(
                  createCarrierData[language].full_name,
                  createCarrierData[language].short_name,
                  createCarrierData.city_id,
                  createCarrierData[language].slogan,
                  selectedMediaId || "",
                  language,
                  { ...colorFields(createCarrierData), main_color: val }
                )
              }
            />
            <p className="text-xs text-gray-500 pl-1">
              Используется в: виджет обращений, значки на карте, скопление достопримечательностей на карте, информационный виджет
            </p>
          </div>
          <div className="flex flex-col gap-1">
            <ColorPickerField
              label="Левый цвет"
              value={createCarrierData.left_color}
              onChange={(val) =>
                setCreateCarrierData(
                  createCarrierData[language].full_name,
                  createCarrierData[language].short_name,
                  createCarrierData.city_id,
                  createCarrierData[language].slogan,
                  selectedMediaId || "",
                  language,
                  { ...colorFields(createCarrierData), left_color: val }
                )
              }
            />
            <p className="text-xs text-gray-500 pl-1">
              Используется в: боковое меню, левый виджет достопримечательности
            </p>
          </div>
          <div className="flex flex-col gap-1">
            <ColorPickerField
              label="Правый цвет"
              value={createCarrierData.right_color}
              onChange={(val) =>
                setCreateCarrierData(
                  createCarrierData[language].full_name,
                  createCarrierData[language].short_name,
                  createCarrierData.city_id,
                  createCarrierData[language].slogan,
                  selectedMediaId || "",
                  language,
                  { ...colorFields(createCarrierData), right_color: val }
                )
              }
            />
            <p className="text-xs text-gray-500 pl-1">
              Используется в: список достопримечательностей, страница достопримечательности
            </p>
          </div>
        </div>

        <div className="w-full flex flex-col gap-4 max-w-[300px] mx-auto">
          <ImageUploadCard
            title="Логотип перевозчика"
            imageKey="thumbnail"
            imageUrl={effectiveLogoUrl}
            onImageClick={() => {
              setIsPreviewMediaOpen(true);
              setMediaId(effectiveLogoUrl ?? "");
            }}
            onDeleteImageClick={() => {
              setSelectedMediaId(null);
              setActiveMenuType(null);
              setCreateCarrierData(
                createCarrierData[language].full_name,
                createCarrierData[language].short_name,
                createCarrierData.city_id,
                createCarrierData[language].slogan,
                "",
                language,
              );
            }}
            onSelectFileClick={() => {
              setActiveMenuType("image");
              setIsSelectMediaOpen(true);
            }}
            setUploadMediaOpen={() => {
              setIsUploadMediaOpen(true);
              setActiveMenuType("image");
            }}
          />
        </div>

        <Button
          variant="contained"
          className="w-min flex gap-2 items-center"
          startIcon={<Save size={20} />}
          onClick={handleCreate}
          disabled={
            isLoading ||
            !createCarrierData[language].full_name ||
            !createCarrierData[language].short_name ||
            !createCarrierData.city_id
          }
        >
          {isLoading ? (
            <Loader2 size={20} className="animate-spin" />
          ) : (
            "Создать"
          )}
        </Button>
      </div>

      <SelectMediaDialog
        open={isSelectMediaOpen}
        onClose={() => setIsSelectMediaOpen(false)}
        onSelectMedia={handleMediaSelect}
        mediaType={1}
      />

      <UploadMediaDialog
        open={isUploadMediaOpen}
        onClose={() => setIsUploadMediaOpen(false)}
        contextObjectName={createCarrierData[language].full_name}
        contextType="carrier"
        afterUpload={handleMediaSelect}
        hardcodeType={activeMenuType}
      />

      <PreviewMediaDialog
        open={isPreviewMediaOpen}
        onClose={() => setIsPreviewMediaOpen(false)}
        mediaId={mediaId}
      />
    </Paper>
  );
});
