import { useCallback, useMemo, useState } from "react";
import { Lock, Loader2 } from "lucide-react";
import { toast } from "sonner";
import {
  ResizablePanel,
  ResizablePanelGroup,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  useAuth,
  cn,
  reviveContributionDraft,
  DraftProvider,
  REPORT_STEP_SESSION_KEY,
  type ReviewDraftTabs,
  type ApplicationFormState,
  type InitiativeFormState,
} from "@ump/shared";
import InitiativeReportForm from "@/components/InitiativeReportForm";
import InitiativeApplicationForm from "@/components/InitiativeApplicationForm";
import ContributionConfirmationForm from "@/components/ContributionConfirmationForm";
import InitiativeEvaluationForm from "@/components/InitiativeEvaluationForm";
import { ReviewPanel } from "@/components/applicant/initiative-draft/ReviewPanel";
import { useApplicantRegistrationState } from "@/hooks/useApplicantRegistrationState";

/** Debounced POST per tab to `/api/v1/application-drafts` so drafts exist before « Tiếp theo » and stay in sync for Lịch sử (mở / sửa / xóa). */
const DRAFT_AUTOSAVE_MS = 2000;

/**
 * Applicant-only workspace: Báo cáo → Đơn → Đóng góp → Xem lại (drafts persisted to Postgres via `/api/v1/application-drafts`).
 */
export function ApplicantRegistrationDashboard() {
  const {
    applicationCaseId,
    draftTabs,
    reportStepCompleted,
    activeApplicantTab,
    setActiveApplicantTab,
    applicantDraftMountKey,
    draftLoadStatus,
    persistDraft,
    persistAllDraftTabs,
    handleReportNext,
  } = useApplicantRegistrationState();

  /** Stable handlers so autosave effects in tab forms do not reset debounce timers on unrelated parent renders. */
  const saveReportTabDraft = useCallback(
    (data: InitiativeFormState) => persistDraft("report", data as unknown as Record<string, unknown>),
    [persistDraft],
  );
  const saveApplicationTabDraft = useCallback(
    (data: ApplicationFormState) =>
      persistDraft("application", data as unknown as Record<string, unknown>),
    [persistDraft],
  );
  const saveContributionTabDraft = useCallback(
    (data: unknown) => persistDraft("contribution", data as Record<string, unknown>),
    [persistDraft],
  );

  const [verificationRequest, setVerificationRequest] = useState<{
    fieldName: string;
    content: string;
  } | null>(null);

  const { hasPermission } = useAuth();

  const canViewEvaluation = hasPermission("evaluation.view");
  const canViewChat = hasPermission("chat.view");
  const canVerify = hasPermission("application.verify");
  const canEditApplication = hasPermission("application.edit");
  const isViewOnly = !canEditApplication && hasPermission("application.view");

  const sessionReportDone =
    typeof window !== "undefined" &&
    (() => {
      try {
        return sessionStorage.getItem(REPORT_STEP_SESSION_KEY) === "1";
      } catch {
        return false;
      }
    })();

  const reportGateOpen = reportStepCompleted || sessionReportDone;
  const lockTabsAfterReport = canEditApplication && !reportGateOpen;

  const handleApplicantTabChange = (value: string) => {
    if (value === "report" || !lockTabsAfterReport) {
      setActiveApplicantTab(value);
      return;
    }
    toast.error(
      "Vui lòng hoàn thành tab Báo cáo, xác nhận cam kết và bấm « Tiếp theo » trước khi mở tab khác.",
    );
  };

  const handleVerify = useCallback(
    (fieldName: string, content: string) => {
      if (canVerify) setVerificationRequest({ fieldName, content });
    },
    [canVerify],
  );

  const lockedTabTriggerClass = lockTabsAfterReport
    ? "pointer-events-none cursor-not-allowed opacity-50"
    : undefined;

  const mainPanelSize = canViewChat ? 70 : 100;
  const chatPanelSize = canViewChat ? 30 : 0;

  const showDraftLoading = Boolean(applicationCaseId) && draftLoadStatus === "loading";

  const reviewFallbackDraftTabs = useMemo(
    (): ReviewDraftTabs => ({
      application: draftTabs.application,
      report: draftTabs.report,
    }),
    [draftTabs.application, draftTabs.report],
  );

  return (
    <div className="flex h-[calc(100vh-4rem)] overflow-hidden animate-fade-in">
      {draftLoadStatus === "error" ? (
        <div
          className="border-b border-destructive/40 bg-destructive/10 px-4 py-2 text-center text-sm text-destructive"
          role="alert"
        >
          Không tải được bản nháp từ máy chủ. Hãy tải lại trang hoặc đăng nhập lại.
        </div>
      ) : null}
      {showDraftLoading ? (
        <div className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-[1px]">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" aria-hidden />
          <p className="text-sm text-muted-foreground">Đang tải bản nháp từ máy chủ…</p>
        </div>
      ) : null}

      <ResizablePanelGroup direction="horizontal" className="h-full overflow-hidden">
        <ResizablePanel defaultSize={mainPanelSize} minSize={0}>
          <div className="h-full overflow-auto p-6">
            <DraftProvider
              key={applicantDraftMountKey}
              caseId={applicationCaseId || undefined}
              seedApplication={(draftTabs.application ?? undefined) as Record<string, unknown> | undefined}
              seedReport={(draftTabs.report ?? undefined) as Record<string, unknown> | undefined}
              preferLocalSnapshot={false}
            >
              <Tabs
                value={activeApplicantTab}
                onValueChange={handleApplicantTabChange}
                className="w-full"
                key={reportGateOpen ? "report-gate-open" : "report-gate-locked"}
              >
                <TabsList className="mb-4 flex-wrap h-auto gap-1">
                  <TabsTrigger value="report">Báo cáo Mô tả Sáng kiến</TabsTrigger>
                  <TabsTrigger value="application" className={lockedTabTriggerClass} aria-disabled={lockTabsAfterReport}>
                    Đơn Đề nghị Công nhận
                  </TabsTrigger>
                  <TabsTrigger value="contribution" className={lockedTabTriggerClass} aria-disabled={lockTabsAfterReport}>
                    Xác nhận Tỷ lệ Đóng góp
                  </TabsTrigger>
                  <TabsTrigger value="review" className={lockedTabTriggerClass} aria-disabled={lockTabsAfterReport}>
                    Xem lại & tải PDF
                  </TabsTrigger>
                  {canViewEvaluation && (
                    <TabsTrigger
                      value="evaluation"
                      className={cn("gap-1", lockedTabTriggerClass)}
                      aria-disabled={lockTabsAfterReport}
                    >
                      <Lock size={14} />
                      Phiếu Đánh Giá
                    </TabsTrigger>
                  )}
                </TabsList>
                <TabsContent value="report">
                  <InitiativeReportForm
                    onVerify={canVerify ? handleVerify : undefined}
                    readOnly={isViewOnly}
                    showVerifyButton={canVerify}
                    initialDraft={draftTabs.report as Partial<InitiativeFormState> | undefined}
                    onSaveDraft={saveReportTabDraft}
                    autoSaveDebounceMs={isViewOnly ? undefined : DRAFT_AUTOSAVE_MS}
                    onNext={handleReportNext}
                  />
                </TabsContent>
                <TabsContent value="application">
                  <InitiativeApplicationForm
                    onVerify={canVerify ? handleVerify : undefined}
                    readOnly={isViewOnly}
                    showVerifyButton={canVerify}
                    initialDraft={draftTabs.application as Partial<ApplicationFormState> | undefined}
                    onSaveDraft={saveApplicationTabDraft}
                    autoSaveDebounceMs={isViewOnly ? undefined : DRAFT_AUTOSAVE_MS}
                    onNext={() => setActiveApplicantTab("contribution")}
                  />
                </TabsContent>
                <TabsContent value="contribution">
                  <ContributionConfirmationForm
                    onVerify={canVerify ? handleVerify : undefined}
                    readOnly={isViewOnly}
                    showVerifyButton={canVerify}
                    initialDraft={reviveContributionDraft(draftTabs.contribution)}
                    onSaveDraft={saveContributionTabDraft}
                    autoSaveDebounceMs={isViewOnly ? undefined : DRAFT_AUTOSAVE_MS}
                    onNext={() => setActiveApplicantTab("review")}
                  />
                </TabsContent>
                <TabsContent value="review">
                  <ReviewPanel
                    caseId={applicationCaseId || undefined}
                    contributionDraft={draftTabs.contribution}
                    fallbackDraftTabs={reviewFallbackDraftTabs}
                    onSaveAllDrafts={persistAllDraftTabs}
                  />
                </TabsContent>
                {canViewEvaluation && (
                  <TabsContent value="evaluation">
                    <InitiativeEvaluationForm onVerify={canVerify ? handleVerify : undefined} />
                  </TabsContent>
                )}
              </Tabs>
            </DraftProvider>
          </div>
        </ResizablePanel>
      </ResizablePanelGroup>
    </div>
  );
}
