import { useEffect, useState, useRef, useCallback } from "react";
import {
  HeaderFooterResponseDto,
  headerFooterService,
  CreateHeaderFooterPayload,
  HeaderFooterChangeStatusPayload,
} from "@/user-management/services/api/headerFooterService";
import { Card } from "@/shared/common/ui/card";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Label } from "@/shared/common/ui/label";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Plus } from "lucide-react";
import { toast } from "sonner";
import i18n from "@/i18n";
import { t } from "i18next";
import { useQueryClient } from "@tanstack/react-query";
import { presignedAxios } from "@/shared/services/presignedAxios";
import useSettings from "@/record-management/components/hooks/useSettings";
import { OrganizationsPositions } from "@/record-management/services/api/departmentService";
import { MultiSelect } from "@/shared/common/ui/multi-select";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { KeyValue } from "@/record-management/types/recordSelectTypes";
import { FormSelectField } from "@/shared/common/form/fields/FormFields";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { useLocalizedName } from "@/shared/common/localizedName";

interface Props {
  unitId: string;
}

const HeaderAndFooter = ({ unitId }: Props) => {
  const [headers, setHeaders] = useState<HeaderFooterResponseDto[]>([]);
  const [footers, setFooters] = useState<HeaderFooterResponseDto[]>([]);
  const [loading, setLoading] = useState(true);
  const [newName, setNewName] = useState("");
  const [newFile, setNewFile] = useState<File | null>(null);
  const [newType, setNewType] = useState<"header" | "footer">("header");
  const [newPreview, setNewPreview] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const queryClient = useQueryClient();
  const lang = i18n.language;
  const [selectedPositions, setSelectedPositions] = useState<string[]>([]);

  const { data: unitConfigData } = useUnitConfiguration(unitId ?? "", {
    enabled: !!unitId,
  });
  const unitConfig = unitConfigData?.data?.items?.[0];
  const canCreateDirectRecord = unitConfig?.canCreateDirectRecord ?? false;
  const localizedName = useLocalizedName();
  const [selectedRecordType, setSelectedRecordType] = useState<string | null>(
    null,
  );
  const isDirectRecordType = (item: {
    name?: { en?: string; am?: string };
    key?: string;
  }) => {
    const key = String(item.key || "").toLowerCase();
    const rawName = [item.name?.en, item.name?.am]
      .filter(Boolean)
      .join(" ")
      .toLowerCase();
    return key.includes("direct") || rawName.includes("direct");
  };

  const { recordTypes } = useSettings();
  const { allDepratments } = useSettings();
  const localizedFormName = useCallback(
    (name?: { am: string; en: string }) => {
      if (!name) return "";
      return lang === "am" ? name.am || name.en : name.en || name.am;
    },
    [lang],
  );
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [headerListRes, footerListRes] = await Promise.all([
        headerFooterService.getHeadersByUnitId(unitId),
        headerFooterService.getFootersByUnitId(unitId),
      ]);

      const activeUploadedHeaders = headerListRes.data.items.filter(
        (item) => item.isCurrent && item.uploadedSuccessfully,
      );
      const activeUploadedFooters = footerListRes.data.items.filter(
        (item) => item.isCurrent && item.uploadedSuccessfully,
      );

      const withPresigned = async (
        items: HeaderFooterResponseDto[],
        type: "header" | "footer",
      ) =>
        Promise.all(
          items.map(async (item) => {
            try {
              const detail =
                type === "header"
                  ? await headerFooterService.getHeaderById(item.id)
                  : await headerFooterService.getFooterById(item.id);
              return { ...item, presigned: detail.data.presigned };
            } catch {
              return item;
            }
          }),
        );

      const [activeHeaders, activeFooters] = await Promise.all([
        withPresigned(activeUploadedHeaders, "header"),
        withPresigned(activeUploadedFooters, "footer"),
      ]);

      setHeaders(activeHeaders);
      setFooters(activeFooters);
    } catch {
      toast.error(t("contentManagement.failedToLoadHeaderFooter"));
    } finally {
      setLoading(false);
    }
  }, [unitId]);

  const handleStatusChange = async (
    id: string,
    type: "header" | "footer",
    isCurrent: boolean,
  ) => {
    try {
      const payload: HeaderFooterChangeStatusPayload = { isCurrent };

      if (type === "header") {
        await headerFooterService.changeHeaderStatus(id, payload);
      } else {
        await headerFooterService.changeFooterStatus(id, payload);
      }

      // Invalidate the query cache so record forms immediately reflect the changes
      queryClient.invalidateQueries({
        queryKey: ["headers-footers", unitId],
      });

      toast.success(t("contentManagement.statusChanged"));
      fetchData();
    } catch {
      toast.error(t("contentManagement.statusChangeFailed"));
    }
  };

  const handleUpload = async () => {
    if (!newName || !newFile) {
      setError(t("contentManagement.provideMsg"));
      return;
    }

    setUploading(true);
    setError(null);

    try {
      const created = await (newType === "header"
        ? headerFooterService.uploadAndCreateHeader(
            newFile,
            newName,
            unitId,
            selectedPositions,
            selectedRecordType,
          )
        : headerFooterService.uploadAndCreateFooter(
            newFile,
            newName,
            unitId,
            selectedPositions,
            selectedRecordType,
          ));

      // Make the newly uploaded resource active immediately.
      if (created?.id) {
        if (newType === "header") {
          await headerFooterService.changeHeaderStatus(created.id, {
            isCurrent: true,
          });
        } else {
          await headerFooterService.changeFooterStatus(created.id, {
            isCurrent: true,
          });
        }
      }

      toast.success(`${newType} ${t("contentManagement.uploadSuccess")}`);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
      setNewFile(null);
      setNewName("");
      setNewPreview(null);
      setError(null);
      setSelectedPositions([]);
      setSelectedRecordType(null);
      fetchData();
    } catch (err) {
      console.error(err);
      setError(t("contentManagement.uploadFailed"));
      toast.error(t("contentManagement.uploadFailed"));
    } finally {
      setUploading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const recordTypeOptions: KeyValue[] =
    recordTypes
      ?.filter((item: { name?: { en?: string; am?: string }; key?: string }) =>
        canCreateDirectRecord ? true : !isDirectRecordType(item),
      )
      .map((item: { name: { en: string; am: string }; key: string }) => ({
        label:
          item.key == "direct"
            ? localizedName({ en: "Direct Letter", am: "ቀጥታ ደብዳቤ" })
            : localizedName(item.name),
        value: item.key,
      })) || [];

  const renderList = (
    title: string,
    items: HeaderFooterResponseDto[],
    type: "header" | "footer",
  ) => (
    <Card className="p-6 border shadow-sm dark:border-gray-700 dark:bg-gray-800">
      <div className="flex items-center justify-between mb-6">
        <h2 className="font-semibold text-xl dark:text-white">{title}</h2>
        <span className="text-sm text-muted-foreground dark:text-gray-400">
          {items.length} {items.length === 1 ? "item" : "items"}
        </span>
      </div>
      {loading ? (
        <Skeleton className="h-40" />
      ) : items.length === 0 ? (
        <div className="text-center py-8">
          <div className="w-16 h-16 mx-auto mb-4 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center">
            <span className="text-2xl text-gray-400 dark:text-gray-500">
              {type === "header" ? "📄" : "📋"}
            </span>
          </div>
          <p className="text-sm text-muted-foreground dark:text-gray-400 mb-2">
            No {title.toLowerCase()} found
          </p>
          <p className="text-xs text-muted-foreground dark:text-gray-500">
            Upload your first {type} using the form below
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {items.map((item) => (
            <div
              key={item.id}
              className={`border rounded-lg p-4 ${
                item.isCurrent
                  ? "bg-primary-50 dark:bg-primary-900/30 border-primary-200 dark:border-primary-800 shadow-sm"
                  : "bg-white dark:bg-gray-700"
              }`}>
              {/* Header with name and status */}
              <div className="flex items-start justify-between mb-3">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-semibold text-lg truncate dark:text-white">
                      {lang === "en" ? item.name.en : item.name.am}
                    </h3>
                    {item.isCurrent && (
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-100 dark:bg-primary-900/50 text-primary-800 dark:text-primary-300 flex-shrink-0">
                        {t("contentManagement.currentlyActive")}
                      </span>
                    )}
                  </div>
                  <p className="text-sm text-muted-foreground dark:text-gray-400 truncate">
                    {item.fileInfo.fileName}
                  </p>
                </div>
              </div>

              {/* Preview and Actions */}
              <div className="flex items-center justify-between gap-4">
                {/* Preview Image */}
                {item.presigned && (
                  <div className="flex-shrink-0">
                    <div className="w-24 h-16 border rounded-md overflow-hidden bg-gray-50 dark:bg-gray-600">
                      <img
                        src={item.presigned}
                        alt={`${type} Preview`}
                        className="w-full h-full object-contain"
                      />
                    </div>
                  </div>
                )}

                {/* Actions */}
                <div className="flex items-center gap-2 ml-auto">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleStatusChange(item.id, type, false)}
                    className="text-red-600 dark:text-red-400 border-red-300 dark:border-red-700 hover:bg-red-50 dark:hover:bg-red-900/30 whitespace-nowrap">
                    {t("contentManagement.delete")}
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </Card>
  );

  return (
    <div className="space-y-8">
      <div className="grid lg:grid-cols-2 gap-8">
        {renderList("Headers", headers, "header")}
        {renderList("Footers", footers, "footer")}
      </div>

      <Card className="p-4 border shadow-sm space-y-4 dark:border-gray-700 dark:bg-gray-800">
        <h2 className="font-semibold text-lg flex items-center gap-2 dark:text-white">
          <Plus className="h-5 w-5" /> {t("contentManagement.addHeaderFooter")}
        </h2>
        <div className="grid md:grid-cols-3 gap-4">
          <div>
            <Label className="dark:text-gray-200">
              {t("contentManagement.name")}
            </Label>
            <Input
              value={newName}
              onChange={(e) => {
                setNewName(e.target.value);
                setError(null);
              }}
              placeholder={t("contentManagement.name")}
              disabled={uploading}
              className="dark:bg-gray-700 dark:border-gray-600 dark:text-white"
            />
          </div>

          <div>
            <Label className="dark:text-gray-200">
              {t("contentManagement.type")}
            </Label>
            <select
              value={newType}
              onChange={(e) =>
                setNewType(e.target.value as "header" | "footer")
              }
              className="w-full rounded border px-3 py-2 text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              disabled={uploading}>
              <option value="header">{t("contentManagement.header")}</option>
              <option value="footer">{t("contentManagement.footer")}</option>
            </select>
          </div>

          <div>
            <Label className="dark:text-gray-200">
              {t("contentManagement.uploadFile")}
            </Label>
            <Input
              type="file"
              accept="image/*"
              ref={fileInputRef}
              onChange={(e) => {
                const file = e.target.files?.[0] || null;
                if (file) {
                  const maxSizeMB = 5; // for example, 2 MB
                  if (file.size > maxSizeMB * 1024 * 1024) {
                    setError(`File size must be less than ${maxSizeMB} MB`);
                    if (fileInputRef.current) fileInputRef.current.value = "";
                    setNewFile(null);
                    setNewPreview(null);
                    return;
                  }
                  setNewFile(file);
                  setNewPreview(URL.createObjectURL(file));
                } else {
                  setNewFile(null);
                  setNewPreview(null);
                }
                setError(null);
              }}
              disabled={uploading}
            />
          </div>
          <div>
            <Label className="dark:text-gray-200">
              {t("contentManagement.positions")}
            </Label>
            <MultiSelect
              options={
                (allDepratments as OrganizationsPositions[] | undefined)?.map(
                  (dept) => ({
                    label: localizedFormName(dept.name),
                    value: dept.id,
                  }),
                ) ?? []
              }
              value={selectedPositions}
              onValueChange={setSelectedPositions}
              placeholder={t("contentManagement.selectPositions")}
              maxCount={5}
              className="w-full max-w-full sm:max-w-md overflow-x-auto"
              animation={0}
            />
          </div>
          <div>
            <Label className="dark:text-gray-200">
              {t("addRecord.Record Type")}
            </Label>
            <Select
              value={selectedRecordType ?? ""}
              onValueChange={(val) => setSelectedRecordType(val || null)}>
              <SelectTrigger>
                <SelectValue placeholder={t("addRecord.Select Record Type")} />
              </SelectTrigger>
              <SelectContent>
                {recordTypeOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {newPreview && (
          <div className="mt-2">
            <Label className="dark:text-gray-200">
              {t("contentManagement.preview")}
            </Label>
            <div className="border rounded p-2 inline-block mt-1 dark:border-gray-600">
              <img
                src={newPreview}
                alt="Preview"
                className="h-24 object-contain rounded"
              />
            </div>
          </div>
        )}

        {error && <p className="text-sm text-red-500">{error}</p>}

        <Button
          onClick={handleUpload}
          disabled={uploading}
          className="bg-primary hover:bg-primary/90 text-primary-foreground w-full">
          {uploading
            ? t("PDF.uploading")
            : `${t("signatureUpload.upload")} ${newType}`}
        </Button>
      </Card>
    </div>
  );
};

export default HeaderAndFooter;
