import { useState, useMemo, useEffect } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { DataTable } from "@/record-management/common/DataTable";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { FilePlus2, Search } from "lucide-react";
import { t } from "i18next";
import { portalOutgoingColumn } from "./portalOutgoingColumn";
import { useExternalPortal } from "@/external-portal/hooks/useCreateExternalLetterRecord";
import Loader from "@/record-management/common/loader";
import { useUser } from "@/shared/context/UserContext";
import { useLocalizedName } from "@/shared/common/localizedName";
import { hasComplaintVerification } from "@/complaints/utils/complaintVerificationStorage";
import { COMPLAINT_SUBMIT_PATH } from "@/complaints/utils/complaintRoutes";
type FilterType = "Reference" | "From" | "Subject" | "letterNumber";

const PortalOutgoing = () => {
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [searchQuery, setSearchQuery] = useState("");
  const [showRegistrationAlert, setShowRegistrationAlert] = useState(false);
  const userDetails = useUser();
  const localizedName = useLocalizedName();
  const hasCompletedRegistration = userDetails?.hasFinishedRegistration;
  const navigate = useNavigate();
  const location = useLocation();
  const complaintSessionActive = hasComplaintVerification();
  const showComplaintPrompt =
    complaintSessionActive ||
    Boolean(
      (location.state as { fromComplaintVerification?: boolean } | null)
        ?.fromComplaintVerification,
    );

  useEffect(() => {
    if (!hasCompletedRegistration && !complaintSessionActive) {
      setShowRegistrationAlert(true);
    } else {
      setShowRegistrationAlert(false);
    }
  }, [complaintSessionActive, hasCompletedRegistration]);

  const [filterType, setFilterType] = useState<FilterType>("Reference");
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });
  const params: Record<string, any> = {
    skip: pagination.pageIndex * pagination.pageSize,
    take: pagination.pageSize,
    orderBy: "record.createdAt:DESC",
  };
  const {
    ExternalLetters,
    isFetchingLetters,
    ExternalCount,
    refetchExternalLetters,
  } = useExternalPortal(params);

  const statusOptions = [{ value: "", label: t("statusBar.All") }];

  const filteredRecords = useMemo(() => {
    let filtered = ExternalLetters;

    if (statusFilter) {
      filtered = filtered.filter(
        (record: any) => record.status === statusFilter,
      );
    }

    if (!searchQuery) return filtered;

    const query = searchQuery.toLowerCase();

    return filtered.filter((record: any) => {
      switch (filterType) {
        case "Reference":
          return record.letterNumber?.toLowerCase().includes(query);
        case "Subject":
          return record.content[0]?.subject.toLowerCase().includes(query);
        default:
          return true;
      }
    });
  }, [ExternalLetters, statusFilter, searchQuery, filterType]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
  };

  const handleFilterChange = (value: FilterType) => {
    setFilterType(value);
  };

  return (
    <div className="min-h-screen w-full bg-slate-50 py-6 md:py-8">
      <div className="mx-auto max-w-6xl px-4 md:px-6">
        <div className="mb-6 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
          <div>
            <h1 className="text-2xl font-bold tracking-tight text-slate-900 md:text-3xl">
              {t("nav.myRecord")}
            </h1>
            <p className="mt-1 text-sm text-slate-600">
              {t("complaint.fayda.formSubtitle")}
            </p>
          </div>
          <Link to={COMPLAINT_SUBMIT_PATH}>
            <Button className="h-11 rounded-lg px-5 shadow-sm bg-primary text-primary-foreground hover:bg-primary/90">
              <FilePlus2 className="mr-2 h-4 w-4" />
              {complaintSessionActive
                ? t("complaint.submit")
                : t("userRecord.Add Record")}
            </Button>
          </Link>
        </div>

        {showComplaintPrompt ? (
          <div className="mb-6 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-900">
            {t("complaint.choice.prompt")}{" "}
            <Link
              to={COMPLAINT_SUBMIT_PATH}
              className="font-semibold underline underline-offset-2">
              {t("complaint.submit")}
            </Link>
          </div>
        ) : null}

        {showRegistrationAlert ? (
          <div className="mb-6 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
            {t("registration.registrationRequired")}{" "}
            <button
              type="button"
              className="font-semibold underline underline-offset-2"
              onClick={() => navigate("/external-portal/upload-documents")}>
              {t("registration.uploadDocuments")}
            </button>
          </div>
        ) : null}

        <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm md:p-5">
          <div className="mb-5 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div className="flex flex-wrap gap-2">
              {statusOptions.map((option) => (
                <Button
                  key={option.value}
                  variant={statusFilter === option.value ? "linkActive" : "link"}
                  onClick={() => setStatusFilter(option.value)}
                  className="rounded-md">
                  {option.label}
                </Button>
              ))}
            </div>

            <div className="flex w-full flex-col gap-3 sm:flex-row lg:w-auto">
              <Select value={filterType} onValueChange={handleFilterChange}>
                <SelectTrigger className="w-full sm:w-[180px]">
                  <SelectValue placeholder={t("userRecord.Filter by")} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Subject">
                    {t("userRecord.Subject")}
                  </SelectItem>
                  <SelectItem value="Reference">
                    {t("userRecord.Letter Number")}
                  </SelectItem>
                </SelectContent>
              </Select>
              <div className="relative w-full sm:min-w-[240px]">
                <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <Input
                  className="pl-9"
                  type="text"
                  placeholder={`${t("userRecord.Search")} ${filterType.toLowerCase()}`}
                  value={searchQuery}
                  onChange={handleSearchChange}
                />
              </div>
            </div>
          </div>

          {isFetchingLetters ? <Loader /> : null}

          <DataTable
            tableName="External Records"
            columns={portalOutgoingColumn(
              localizedName as (name?: { am?: string; en?: string }) => string,
            )}
            data={filteredRecords}
            toolBarPosition="right"
            totalCount={ExternalCount}
            pagination={pagination}
            setPagination={setPagination}
            refresh={refetchExternalLetters}
          />
        </div>
      </div>
    </div>
  );
};

export default PortalOutgoing;
