"use client";

import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import clsx from "clsx";
import { CalendarDays, FolderKanban, ListTodo, RefreshCw, Share2, Trash2 } from "lucide-react";
import { api } from "@/lib/api";
import { getNativeZimbraAddonState } from "@/lib/addons/zimbra";
import { useBranding } from "@/lib/branding";
import { createTranslator, DEFAULT_LOCALE } from "@/lib/i18n";
import type { FolderShare, ProductConfig } from "@/lib/types";

type NativeZimbraAddonProps = {
  product?: ProductConfig;
  t?: ReturnType<typeof createTranslator>;
};

export function NativeZimbraAddonTab({ product, t = createTranslator(DEFAULT_LOCALE) }: NativeZimbraAddonProps) {
  const branding = useBranding();
  const queryClient = useQueryClient();
  const { calendarEnabled, tasksEnabled, briefcaseEnabled } = getNativeZimbraAddonState(product);
  const [shareEmail, setShareEmail] = useState("");
  const [sharePermissions, setSharePermissions] = useState("r");
  const calendarShares = useQuery({
    queryKey: ["native-zimbra-calendar-shares"],
    queryFn: () => api.nativeZimbraCalendarShares(),
    enabled: calendarEnabled,
    staleTime: 30_000,
    refetchOnWindowFocus: false,
  });
  const shareCalendar = useMutation({
    mutationFn: api.nativeZimbraShareCalendar,
    onSuccess: async () => {
      setShareEmail("");
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares"] });
    },
  });
  const revokeCalendarShare = useMutation({
    mutationFn: api.nativeZimbraRevokeCalendarShare,
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares"] });
    },
  });

  useEffect(() => {
    if (!calendarEnabled) {
      setShareEmail("");
      setSharePermissions("r");
    }
  }, [calendarEnabled]);

  return (
    <section className="min-h-0 overflow-auto p-2 lg:p-4">
      <div className="control-surface grid gap-4 rounded-xl p-3 sm:p-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">{t("addon.productivityStatus")}</p>
            <h2 className="text-2xl font-black">{t("addon.productivityTitle")}</h2>
          </div>
          <button type="button" className="theme-button-soft h-10 px-4 text-sm">
            <RefreshCw size={16} />
            {t("addon.refreshStatus")}
          </button>
        </div>

        <div className="grid gap-4 xl:grid-cols-3">
          <article className={clsx("rounded-xl border p-4", calendarEnabled ? "border-emerald-200 bg-emerald-50/40" : "border-slate-200 bg-slate-50")}>
            <div className="flex items-start gap-3">
              <div className={clsx("grid h-10 w-10 place-items-center rounded-lg", calendarEnabled ? "bg-white text-emerald-700" : "bg-white text-slate-400")}>
                <CalendarDays size={18} />
              </div>
              <div className="min-w-0">
                <p className="text-sm font-black text-slate-900">{t("nav.calendar")}</p>
                <p className={clsx("mt-1 text-xs font-black uppercase tracking-[0.08em]", calendarEnabled ? "text-emerald-700" : "text-slate-400")}>{calendarEnabled ? t("security.enabled") : t("addon.notEnabled")}</p>
              </div>
            </div>
          </article>

          <article className={clsx("rounded-xl border p-4", tasksEnabled ? "border-emerald-200 bg-emerald-50/40" : "border-slate-200 bg-slate-50")}>
            <div className="flex items-start gap-3">
              <div className={clsx("grid h-10 w-10 place-items-center rounded-lg", tasksEnabled ? "bg-white text-emerald-700" : "bg-white text-slate-400")}>
                <ListTodo size={18} />
              </div>
              <div className="min-w-0">
                <p className="text-sm font-black text-slate-900">{t("nav.task")}</p>
                <p className={clsx("mt-1 text-xs font-black uppercase tracking-[0.08em]", tasksEnabled ? "text-emerald-700" : "text-slate-400")}>{tasksEnabled ? t("security.enabled") : t("addon.notEnabled")}</p>
              </div>
            </div>
          </article>

          <article className={clsx("rounded-xl border p-4", briefcaseEnabled ? "border-emerald-200 bg-emerald-50/40" : "border-slate-200 bg-slate-50")}>
            <div className="flex items-start gap-3">
              <div className={clsx("grid h-10 w-10 place-items-center rounded-lg", briefcaseEnabled ? "bg-white text-emerald-700" : "bg-white text-slate-400")}>
                <FolderKanban size={18} />
              </div>
              <div className="min-w-0">
                <p className="text-sm font-black text-slate-900">Briefcase</p>
                <p className={clsx("mt-1 text-xs font-black uppercase tracking-[0.08em]", briefcaseEnabled ? "text-emerald-700" : "text-slate-400")}>{briefcaseEnabled ? t("security.enabled") : t("addon.notEnabled")}</p>
              </div>
            </div>
          </article>
        </div>

        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">{t("addon.calendarSharing")}</p>
              <h3 className="mt-1 text-lg font-black text-slate-950">{t("calendar.shareCalendar")}</h3>
              <p className="mt-1 max-w-2xl text-sm leading-6 text-slate-600">
                {t("addon.calendarShareHelp")}
              </p>
            </div>
            <button
              type="button"
              className="theme-button-soft h-10 px-4 text-sm"
              onClick={() => void calendarShares.refetch()}
              disabled={!calendarEnabled || calendarShares.isFetching}
            >
              <RefreshCw size={16} className={clsx(calendarShares.isFetching && "animate-spin")} />
              {t("common.refresh")}
            </button>
          </div>

          {!calendarEnabled ? (
            <p className="mt-4 rounded-lg border border-dashed border-slate-200 bg-slate-50 p-4 text-sm font-semibold text-slate-500">
              {t("addon.calendarUnavailable")}
            </p>
          ) : (
            <div className="mt-4 grid gap-4 lg:grid-cols-[minmax(0,320px)_1fr]">
              <form
                className="grid gap-3 rounded-xl border border-slate-200 bg-slate-50 p-4"
                onSubmit={(event) => {
                  event.preventDefault();
                  const email = shareEmail.trim();
                  if (!email) return;
                  void shareCalendar.mutateAsync({ email, permissions: sharePermissions.trim() || "r" });
                }}
              >
                <div className="grid gap-2">
                  <label className="text-sm font-bold text-slate-600">{t("dialog.emailAddress")}</label>
                  <input
                    value={shareEmail}
                    onChange={(event) => setShareEmail(event.target.value)}
                    className="field h-11 w-full"
                    placeholder="person@example.com"
                  />
                </div>
                <div className="grid gap-2">
                  <label className="text-sm font-bold text-slate-600">{t("dialog.permission")}</label>
                  <select value={sharePermissions} onChange={(event) => setSharePermissions(event.target.value)} className="field h-11 w-full">
                    <option value="r">{t("dialog.viewer")}</option>
                    <option value="rwidx">{t("dialog.manager")}</option>
                  </select>
                </div>
                <button type="submit" className="theme-button h-11 px-4 text-sm disabled:opacity-50" disabled={!shareEmail.trim() || shareCalendar.isPending}>
                  <Share2 size={16} />
                  {shareCalendar.isPending ? t("common.sharing") : t("calendar.shareCalendar")}
                </button>
              </form>

              <div className="grid gap-2">
                <div className="flex items-center gap-2">
                  <Share2 size={16} className="text-[var(--accent)]" />
                  <h4 className="text-sm font-black text-slate-900">{t("dialog.currentShares")}</h4>
                </div>
                {calendarShares.isLoading ? (
                  <p className="rounded-lg border border-slate-200 bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("dialog.loadingShares")}</p>
                ) : null}
                {!calendarShares.isLoading && !(calendarShares.data?.shares.length ?? 0) ? (
                  <p className="rounded-lg border border-slate-200 bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("addon.noCalendarShares")}</p>
                ) : null}
                <div className="grid gap-2">
                  {(calendarShares.data?.shares ?? []).map((share: FolderShare) => (
                    <div key={`${share.email}:${share.permissions}`} className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2">
                      <div className="min-w-0">
                        <p className="truncate text-sm font-bold text-slate-900">{share.display_name || share.email || t("dialog.sharedAccess")}</p>
                        <p className="text-xs font-semibold text-slate-500">{share.email || t("sharing.unknownRecipient")}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-black uppercase tracking-[0.08em] text-slate-500">
                          {share.permissions || "r"}
                        </span>
                        <button
                          type="button"
                          className="theme-button-soft h-8 px-3 text-sm text-red-700"
                          disabled={revokeCalendarShare.isPending || !share.email}
                          onClick={() => void revokeCalendarShare.mutateAsync({ email: share.email })}
                        >
                          <Trash2 size={14} />
                          {t("common.revoke")}
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="rounded-xl border border-dashed border-slate-200 bg-white p-4">
          <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">{t("addon.editionBoundary")}</p>
          <p className="mt-2 text-xs font-semibold text-slate-400">
            {t("addon.brand")}: {branding.name}
          </p>
        </div>
      </div>
    </section>
  );
}
