import { EmbedConfigModal, EmbedType } from "@ui/components/EmbedConfigModal";
import { Button } from "@xtablo/ui/components/button";
import {
  Card,
  CardAction,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@xtablo/ui/components/card";
import {
  CheckIcon,
  EditIcon,
  ExternalLinkIcon,
  SettingsIcon,
  TrashIcon,
  XIcon,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { match } from "ts-pattern";
import { EventType, EventTypeConfig, useEventTypes } from "../hooks/event-types";
import { isDev } from "../lib/env";
import { useUser } from "../providers/UserStoreProvider";

export function EventTypeCard({
  eventType,
  handleEditEventType,
}: {
  eventType: EventType;
  handleEditEventType: (id: string, eventType: EventTypeConfig) => void;
}) {
  const { t } = useTranslation("components");
  const { toggleEventType, deleteEventType } = useEventTypes();
  const user = useUser();
  const [isEmbedModalOpen, setIsEmbedModalOpen] = useState(false);

  const getPublicLink = (standardName: string | null, type: EmbedType) => {
    // Sanitize user name for URL (replace spaces with hyphens, lowercase, remove special chars)
    const sanitizedUserName = user.name
      ?.toLowerCase()
      .replace(/\s+/g, "-")
      .replace(/[^a-z0-9-]/g, "");

    const shortUserId = user.id.substring(0, 6);
    // Construct the public booking URL
    const baseUrl = isDev ? "http://localhost:5174" : "https://embed.xtablo.com";
    return match(type)
      .with("embed", () => {
        return `${baseUrl}/embed/${sanitizedUserName}-${shortUserId}/${standardName}`;
      })
      .with("floating", () => {
        return `${baseUrl}/widget/${sanitizedUserName}-${shortUserId}/${standardName}`;
      })
      .with("normal", () => {
        return `${window.location.origin}/book/${sanitizedUserName}-${shortUserId}/${standardName}`;
      })
      .exhaustive();
  };

  return (
    <Card
      key={eventType.id}
      className={`${
        eventType.isActive
          ? "opacity-100 border-[#804EEC]/30 bg-white dark:bg-[#804EEC]/5"
          : "opacity-70 border-[#804EEC]/15"
      } transition-all hover:shadow-[0_10px_25px_rgba(128,78,236,0.18)]`}
    >
      <CardHeader className="min-h-[80px]">
        <CardTitle className="text-lg">{eventType.name}</CardTitle>
        <CardAction>
          <div className="flex gap-2">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setIsEmbedModalOpen(true)}
              className="text-muted-foreground hover:bg-muted hover:text-foreground"
              aria-label={t("eventTypeCard.aria.settings")}
            >
              <SettingsIcon className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() =>
                window.open(getPublicLink(eventType.standardName ?? null, "normal"), "_blank")
              }
              className="text-muted-foreground hover:bg-muted hover:text-foreground"
              aria-label={t("eventTypeCard.aria.preview")}
            >
              <ExternalLinkIcon className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleEditEventType(eventType.id, eventType as EventTypeConfig)}
              className="text-muted-foreground hover:bg-muted hover:text-foreground"
              aria-label={t("eventTypeCard.aria.edit")}
            >
              <EditIcon className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => deleteEventType({ id: eventType.id })}
              className="hover:text-red-500 hover:bg-red-50/10 dark:hover:bg-red-950/10"
              aria-label={t("eventTypeCard.aria.delete")}
            >
              <TrashIcon className="w-4 h-4" />
            </Button>
          </div>
        </CardAction>
      </CardHeader>

      <CardContent className="min-h-[200px]">
        {/* <Text className="text-muted-foreground">{eventType.description}</Text> */}

        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-muted-foreground">{t("eventTypeCard.duration")}</span>
            <span className="font-medium">
              {eventType.duration} {t("eventTypeCard.minutes")}
            </span>
          </div>
          {eventType.bufferTime && (
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t("eventTypeCard.bufferTime")}</span>
              <span className="font-medium">
                {eventType.bufferTime} {t("eventTypeCard.minutes")}
              </span>
            </div>
          )}
          {eventType.maxBookingsPerDay && (
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t("eventTypeCard.maxPerDay")}</span>
              <span className="font-medium">{eventType.maxBookingsPerDay}</span>
            </div>
          )}
          {eventType.minAdvanceBooking && (
            <div className="flex justify-between">
              <span className="text-muted-foreground">{t("eventTypeCard.advanceBooking")}</span>
              <span className="font-medium">
                {eventType.minAdvanceBooking.value}{" "}
                {eventType.minAdvanceBooking.unit === "minutes"
                  ? t("eventTypeCard.minutes")
                  : eventType.minAdvanceBooking.unit === "hours"
                    ? t("eventTypeCard.hours")
                    : t("eventTypeCard.days")}
              </span>
            </div>
          )}
        </div>
      </CardContent>

      <CardFooter className="justify-between border-t border-[#804EEC]/20">
        <span className="text-muted-foreground">{t("eventTypeCard.status")}</span>
        <Button
          variant={eventType.isActive ? "default" : "outline"}
          size="sm"
          onClick={() =>
            toggleEventType({
              id: eventType.id,
              isActive: !eventType.isActive,
            })
          }
          className={`text-sm ${
            eventType.isActive
              ? "bg-[#804EEC] text-white hover:bg-[#6f3fd4]"
              : "border-[#804EEC]/40 text-[#804EEC] hover:bg-[#804EEC]/10 hover:text-[#6f3fd4]"
          }`}
        >
          {eventType.isActive ? <CheckIcon /> : <XIcon />}
          {eventType.isActive ? t("eventTypeCard.active") : t("eventTypeCard.inactive")}
        </Button>
      </CardFooter>

      <EmbedConfigModal
        isOpen={isEmbedModalOpen}
        onClose={() => setIsEmbedModalOpen(false)}
        buildPublicLink={(type: "embed" | "floating" | "normal") =>
          getPublicLink(eventType.standardName ?? null, type)
        }
      />
    </Card>
  );
}
