"use client";

import type React from "react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/shared/common/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Loader2,
  FileCheck,
  ArrowRight,
  ArrowLeft,
  Sparkles,
  CheckCircle2,
} from "lucide-react";
import SealSelector from "./sealSelector";
import { usePendingRecords } from "../hooks/usePendingRecords";
import { fetchRecordById } from "@/record-management/services/api/userRecordService";
import { dispatchRecord } from "@/record-management/services/api/recordOfficerService";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";

import { useRecordTagPrefixes } from "@/user-management/hooks/useRecordTagPrefixes";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Label } from "@/shared/common/ui/label";
import { RecordTagSelector } from "@/user-management/components/content/RecordTagSelector";
interface ConvertRecordProps {
  recordId: string;
}

export interface RecordSummaryDTO {
  id: string;
  recordType: string;
  subject: string;
}

export const mapToRecordSummary = (record: any): RecordSummaryDTO => {
  return {
    id: record.id,
    recordType: record.recordTypeKey,
    subject: record.content?.[0]?.subject || "No subject",
  };
};

const ConvertRecord: React.FC<ConvertRecordProps> = ({ recordId }) => {
  const navigate = useNavigate();
  const [selectedSeal, setSelectedSeal] = useState<string | null>(null);
  const [selectedAttachmentSeal, setSelectedAttachmentSeal] = useState<
    string | null
  >(null);
  const [recordSummary, setRecordSummary] = useState<RecordSummaryDTO | null>(
    null,
  );
  const [selectedTagId, setSelectedTagId] = useState<string>("");
  const [selectedPrefixId, setSelectedPrefixId] = useState<string>("");
  const [skip] = useState(0);
  const pageSize = 100;
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId;

  const { data: unitConfigData, isLoading: isUnitConfigLoading } =
    useUnitConfiguration(unitId ?? "", {
      enabled: !!unitId,
    });
  const unitConfig = unitConfigData?.data?.items?.[0];
  const canHaveTagBasedReferenceNumber =
    unitConfig?.canHaveTagBasedReferenceNumber ?? false;
  const { prefixes, isLoadingPrefixes, isErrorPrefixes } = useRecordTagPrefixes(
    {
      unitId: unitId ?? "",
      recordTagId: selectedTagId || undefined,
      skip,
      take: pageSize,
    },
  );
  const { isLoading, refetch } = usePendingRecords();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  useEffect(() => {
    setSelectedPrefixId("");
  }, [selectedTagId]);

  useEffect(() => {
    if (recordId) {
      fetchRecordById(recordId)
        .then((record) => {
          const summary = mapToRecordSummary(record);
          setRecordSummary(summary);
        })
        .catch((err) => {
          toast.error(`Failed to fetch record: ${err.message}`);
          handleError(err);
        });
    }
  }, [handleError, recordId]);

  const queryClient = useQueryClient();

  const { mutate: convertRecord } = useMutation({
    mutationFn: dispatchRecord,
    onSuccess: () => {
      toast.success(t("convert.recordConverted"));
      queryClient.invalidateQueries({ queryKey: ["outgoingRecords"] });
      navigate("/record-management/recordOfficer/outgoing");
      refetch();
    },
    onError: (error: any) => {
      handleError(error);
    },
  });

  const handleConvert = () => {
    if (!selectedSeal) {
      toast.error(t("convert.selectSeal"));
      return;
    }

    // If tag-based reference numbers are enabled, validate tag and prefix selection
    // if (canHaveTagBasedReferenceNumber) {
    //   if (!selectedTagId) {
    //     toast.error(
    //       t("convert.selectTagRequired", "Please select a reference tag"),
    //     );
    //     return;
    //   }
    //   if (!selectedPrefixId) {
    //     toast.error(
    //       t(
    //         "convert.selectReferenceRequired",
    //         "Please select a reference number",
    //       ),
    //     );
    //     return;
    //   }
    // }
    convertRecord({
      recordId: recordId,
      sealId: selectedSeal,
      ...(selectedAttachmentSeal && {
        attachmentSealId: selectedAttachmentSeal,
      }),
      ...(canHaveTagBasedReferenceNumber &&
        selectedPrefixId && {
          recordPrefixId: selectedPrefixId,
        }),
    });
  };

  return (
    <div className="min-h-screen bg-white dark:bg-slate-950">
      <div className="w-full max-w-4xl mx-auto space-y-6 py-8 px-4 sm:px-6">
        {/* Back Button */}
        <div className="flex justify-start">
          <Button
            onClick={() => navigate(-1)}
            variant="ghost"
            className="flex items-center gap-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-100 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all duration-300 font-semibold text-sm py-2 px-3 shadow-xs hover:shadow-md"
          >
            <ArrowLeft className="h-4 w-4" />
            <span>{t("back", "Back")}</span>
          </Button>
        </div>
        {/* Header Section */}
        <div className="text-center space-y-3">
          <div className="inline-flex items-center justify-center p-3 rounded-2xl bg-primary-600 shadow-lg mb-4">
            <FileCheck className="h-8 w-8 text-white" />
          </div>
          <h1 className="text-4xl font-bold text-slate-900 dark:text-slate-100">
            {t("convert.convertRecord")}
          </h1>
          <p className="text-slate-600 dark:text-slate-400 text-lg max-w-2xl mx-auto">
            Review record details and select a seal to convert and dispatch
          </p>
        </div>

        {/* Main Card */}
        <Card className="border border-slate-200 dark:border-slate-800 shadow-lg bg-white dark:bg-slate-900 rounded-2xl">
          <CardHeader className="border-b border-slate-200 dark:border-slate-800 px-6 sm:px-8 py-6 bg-slate-50 dark:bg-slate-900">
            <div className="flex items-start gap-4">
              <div className="p-2 rounded-xl bg-primary-600 shadow-md flex-shrink-0">
                <Sparkles className="h-5 w-5 text-white" />
              </div>
              <div className="flex-1 min-w-0">
                <CardTitle className="text-xl sm:text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">
                  {t("convert.convertRecord")}
                </CardTitle>
                <p className="text-base text-slate-600 dark:text-slate-400 line-clamp-2">
                  {recordSummary?.subject}
                </p>
              </div>
            </div>
          </CardHeader>

          <CardContent className="space-y-8 px-6 sm:px-8 py-8">
            {/* Record Details Section */}
            <div className="space-y-4 p-6 bg-primary-50 dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700">
              <h3 className="text-sm font-bold text-slate-700 dark:text-slate-300 uppercase tracking-wider flex items-center gap-2 mb-4">
                <div className="w-1 h-5 bg-primary-600 rounded-full" />
                Record Information
              </h3>

              <div className="grid gap-4">
                <div className="flex flex-col sm:flex-row sm:items-center gap-2 p-4 bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary-500 dark:hover:border-primary-600 transition-colors duration-300">
                  <span className="text-sm font-semibold text-slate-600 dark:text-slate-400 min-w-[120px]">
                    {t("convert.subject")}
                  </span>
                  <span className="text-base font-medium text-slate-900 dark:text-slate-100 flex-1">
                    {recordSummary?.subject}
                  </span>
                </div>

                <div className="flex flex-col sm:flex-row sm:items-center gap-2 p-4 bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-700 hover:border-primary-500 dark:hover:border-primary-600 transition-colors duration-300">
                  <span className="text-sm font-semibold text-slate-600 dark:text-slate-400 min-w-[120px]">
                    {t("convert.recordType")}
                  </span>
                  <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-primary-100 dark:bg-primary-900/50 text-primary-700 dark:text-primary-300 border border-primary-200 dark:border-primary-800">
                    {recordSummary?.recordType === "external"
                      ? "External"
                      : "Internal"}
                  </span>
                </div>
              </div>
            </div>

            {/* Tag Based Reference Number Section - Only show if config is enabled */}
            {canHaveTagBasedReferenceNumber && !isUnitConfigLoading && (
              <div className="space-y-4">
                <h3 className="text-sm font-bold text-slate-700 dark:text-slate-300 uppercase tracking-wider flex items-center gap-2">
                  <div className="w-1 h-5 bg-primary-600 rounded-full" />
                  {t("convert.referenceInformation", "Reference Information")}
                </h3>
                <div className="p-6 bg-primary-50 dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 space-y-4">
                  {/* Tag Selection */}
                  <div className="space-y-2">
                    <Label className="text-sm font-semibold">
                      {t("convert.selectTag", "Select Reference Tag")} *
                    </Label>
                    <RecordTagSelector
                      unitId={unitId ?? ""}
                      selectedTagIds={selectedTagId ? [selectedTagId] : []}
                      onChange={(ids) => setSelectedTagId(ids[0] || "")}
                      placeholder={t("nav.selectTag") || "Choose a tag..."}
                      multiple={false}
                    />
                  </div>

                  {/* Reference Number Selection - Only show when tag is selected */}
                  {selectedTagId && (
                    <div className="space-y-2">
                      <Label className="text-sm font-semibold">
                        {t(
                          "convert.selectReferenceNumber",
                          "Select Reference Number",
                        )}{" "}
                        *
                      </Label>
                      {isLoadingPrefixes ? (
                        <div className="flex items-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span className="text-sm text-muted-foreground">
                            {t("common.loading", "Loading...")}
                          </span>
                        </div>
                      ) : isErrorPrefixes ? (
                        <div className="text-sm text-red-600 dark:text-red-400">
                          {t(
                            "common.error",
                            "Failed to load reference numbers",
                          )}
                        </div>
                      ) : prefixes.length === 0 ? (
                        <div className="text-sm text-amber-600 dark:text-amber-400">
                          {t(
                            "convert.noReferenceNumbers",
                            "No reference numbers available for this tag",
                          )}
                        </div>
                      ) : (
                        <Select
                          value={selectedPrefixId}
                          onValueChange={setSelectedPrefixId}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue
                              placeholder={t(
                                "convert.chooseReferenceNumber",
                                "Choose a reference number",
                              )}
                            />
                          </SelectTrigger>
                          <SelectContent>
                            {prefixes.map((prefix) => (
                              <SelectItem key={prefix.id} value={prefix.id}>
                                {prefix.name?.am} / {prefix.name?.en}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Seal Selection Section */}
            <div className="space-y-4">
              <h3 className="text-sm font-bold text-slate-700 dark:text-slate-300 uppercase tracking-wider flex items-center gap-2">
                <div className="w-1 h-5 bg-primary-600 rounded-full" />
                Select Seal
              </h3>
              <div className="p-6 bg-primary-50 dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700">
                <SealSelector
                  selectedSeal={selectedSeal}
                  onSelect={setSelectedSeal}
                />
              </div>
            </div>

            {/* Optional Attachment Seal Selection Section */}
            <div className="space-y-4">
              <h3 className="text-sm font-bold text-slate-700 dark:text-slate-300 uppercase tracking-wider flex items-center gap-2">
                <div className="w-1 h-5 bg-blue-600 rounded-full" />
                Select Seal for Attachments (Optional)
              </h3>
              <div className="p-6 bg-blue-50 dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700">
                <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
                  Use a different seal for attachments if needed. Leave empty to
                  use the same seal as the record.
                </p>
                <SealSelector
                  selectedSeal={selectedAttachmentSeal}
                  onSelect={setSelectedAttachmentSeal}
                />
              </div>
            </div>

            {/* Action Button */}
            <div className="pt-4">
              <Button
                onClick={handleConvert}
                disabled={isLoading || !selectedSeal}
                className="w-full h-14 bg-primary-600 hover:bg-primary-700 text-white shadow-lg hover:shadow-xl transition-all duration-300 rounded-xl text-base font-semibold group/btn disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading ? (
                  <div className="flex items-center gap-3">
                    <Loader2 className="animate-spin h-5 w-5" />
                    <span>Processing...</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-3">
                    <CheckCircle2 className="h-5 w-5 group-hover/btn:scale-110 transition-transform duration-300" />
                    <span>{t("convert.convertAndDispatch")}</span>
                    <ArrowRight className="h-5 w-5 group-hover/btn:translate-x-1 transition-transform duration-300" />
                  </div>
                )}
              </Button>

              {!selectedSeal && (
                <p className="text-sm text-amber-600 dark:text-amber-400 mt-3 text-center flex items-center justify-center gap-2">
                  <span className="inline-block w-1.5 h-1.5 bg-amber-500 rounded-full animate-pulse" />
                  Please select a seal to continue
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Info Card */}
        <div className="p-6 bg-primary-50 dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm">
          <div className="flex items-start gap-4">
            <div className="p-2 rounded-lg bg-primary-100 dark:bg-primary-900/50 flex-shrink-0">
              <svg
                className="h-5 w-5 text-primary-600 dark:text-primary-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
            <div className="flex-1">
              <h4 className="text-sm font-semibold text-primary-900 dark:text-gray-100 mb-1">
                Important Information
              </h4>
              <p className="text-sm text-gray-700 dark:text-gray-300">
                Once converted and dispatched, this record will be moved to the
                outgoing records section. Make sure you've selected the correct
                seal before proceeding.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConvertRecord;
