"use client";

import { useDeferredValue, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ChatBubbleLeftRightIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  ChevronRightIcon,
  TicketIcon,
} from "@heroicons/react/24/outline";
import type { StatItem } from "@/components/molecules/SummaryStats";
import { ChatBubbleLeftRightIcon as ChatBubbleLeftRightIconSolid } from "@heroicons/react/24/solid";
import { PageLayout } from "@/components/templates/PageLayout";
import {
  AnimatedCard,
  SummaryStats,
  FilterDropdown,
  ClearFiltersButton,
} from "@/components/molecules";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import { Button } from "@/components/atoms";
import { EmptyState, SearchEmptyState } from "@/components/atoms/empty-state";
import { useSupportCases } from "@/features/support/hooks/useSupportCases";
import {
  SUPPORT_CASE_PRIORITY,
  SUPPORT_CASE_STATUS,
  type SupportCaseFilter,
} from "@customer-portal/domain/support";
import {
  getCaseStatusIcon,
  getCaseStatusClasses,
  getCasePriorityClasses,
} from "@/features/support/utils";
import { formatIsoRelative } from "@/shared/utils";

export function SupportCasesView() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [priorityFilter, setPriorityFilter] = useState<string>("all");
  const deferredSearchTerm = useDeferredValue(searchTerm);

  const queryFilters = useMemo(() => {
    const nextFilters: SupportCaseFilter = {};
    if (statusFilter !== "all") {
      nextFilters.status = statusFilter;
    }
    if (priorityFilter !== "all") {
      nextFilters.priority = priorityFilter;
    }
    if (deferredSearchTerm.trim()) {
      nextFilters.search = deferredSearchTerm.trim();
    }
    return nextFilters;
  }, [statusFilter, priorityFilter, deferredSearchTerm]);

  const { data, error, refetch } = useSupportCases(queryFilters);
  const cases = data?.cases ?? [];
  const summary = data?.summary ?? { total: 0, open: 0, highPriority: 0, resolved: 0 };

  // Show loading until we have data or an error
  const showLoading = !data && !error;

  const hasActiveFilters =
    statusFilter !== "all" || priorityFilter !== "all" || searchTerm.trim() !== "";

  const statusFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Statuses" },
      ...Object.values(SUPPORT_CASE_STATUS).map(status => ({ value: status, label: status })),
    ],
    []
  );

  const priorityFilterOptions = useMemo(
    () => [
      { value: "all", label: "All Priorities" },
      ...Object.values(SUPPORT_CASE_PRIORITY).map(priority => ({
        value: priority,
        label: priority,
      })),
    ],
    []
  );

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setPriorityFilter("all");
  };

  return (
    <PageLayout
      icon={<ChatBubbleLeftRightIconSolid />}
      title="Support Cases"
      description="Track and manage your support requests"
      loading={showLoading}
      error={error}
      onRetry={() => void refetch()}
      breadcrumbs={[{ label: "Support", href: "/account/support" }, { label: "Cases" }]}
      actions={
        <Button as="a" href="/account/support/new" leftIcon={<TicketIcon className="h-4 w-4" />}>
          New Case
        </Button>
      }
    >
      {/* Summary Stats */}
      <SummaryStats
        variant="inline"
        items={
          [
            {
              icon: <ChatBubbleLeftRightIcon className="h-4 w-4" />,
              label: "Total",
              value: summary.total,
              tone: "muted",
            },
            {
              icon: <ClockIcon className="h-4 w-4" />,
              label: "Open",
              value: summary.open,
              tone: "primary",
            },
            {
              icon: <ExclamationTriangleIcon className="h-4 w-4" />,
              label: "High Priority",
              value: summary.highPriority,
              tone: "warning",
              show: summary.highPriority > 0,
            },
            {
              icon: <CheckCircleIcon className="h-4 w-4" />,
              label: "Resolved",
              value: summary.resolved,
              tone: "success",
            },
          ] satisfies StatItem[]
        }
      />

      {/* Search & Filters */}
      <SearchFilterBar
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Search by case number or subject..."
        filterValue={statusFilter}
        onFilterChange={setStatusFilter}
        filterOptions={statusFilterOptions}
        filterLabel="Filter by status"
      >
        {/* Priority filter as additional child */}
        <FilterDropdown
          value={priorityFilter}
          onChange={setPriorityFilter}
          options={priorityFilterOptions}
          label="Filter by priority"
          width="w-40"
        />

        {/* Clear filters button */}
        <ClearFiltersButton onClick={clearFilters} show={hasActiveFilters} />
      </SearchFilterBar>

      {/* Cases List */}
      {cases.length > 0 ? (
        <div className="border border-border rounded-xl bg-card divide-y divide-border overflow-hidden shadow-[var(--cp-shadow-1)]">
          {cases.map(supportCase => (
            <div
              key={supportCase.id}
              onClick={() => router.push(`/account/support/${supportCase.id}`)}
              className="flex items-center gap-4 p-4 hover:bg-muted cursor-pointer transition-colors group"
            >
              {/* Status Icon */}
              <div className="flex-shrink-0">{getCaseStatusIcon(supportCase.status)}</div>

              {/* Main Content */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-sm font-medium text-primary">
                    #{supportCase.caseNumber}
                  </span>
                  <span className="text-sm text-foreground truncate">{supportCase.subject}</span>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <span
                    className={`inline-flex text-xs px-2 py-0.5 rounded font-medium ${getCaseStatusClasses(supportCase.status)}`}
                  >
                    {supportCase.status}
                  </span>
                  <span
                    className={`inline-flex text-xs px-2 py-0.5 rounded font-medium ${getCasePriorityClasses(supportCase.priority)}`}
                  >
                    {supportCase.priority}
                  </span>
                  {supportCase.category && (
                    <span className="text-xs text-muted-foreground">{supportCase.category}</span>
                  )}
                </div>
              </div>

              {/* Timestamp */}
              <div className="hidden sm:block text-right flex-shrink-0">
                <p className="text-xs text-muted-foreground/70">
                  Updated {formatIsoRelative(supportCase.updatedAt)}
                </p>
              </div>

              {/* Arrow */}
              <ChevronRightIcon className="h-4 w-4 text-muted-foreground/60 group-hover:text-muted-foreground flex-shrink-0 transition-colors" />
            </div>
          ))}
        </div>
      ) : hasActiveFilters ? (
        <AnimatedCard className="p-8" variant="static">
          <SearchEmptyState searchTerm={searchTerm || "filters"} onClearSearch={clearFilters} />
        </AnimatedCard>
      ) : (
        <AnimatedCard className="p-8" variant="static">
          <EmptyState
            icon={<TicketIcon className="h-12 w-12" />}
            title="No support cases found"
            description="You haven't created any support cases yet. Need help? Create a new case."
            action={{
              label: "Create Case",
              onClick: () => router.push("/account/support/new"),
            }}
          />
        </AnimatedCard>
      )}
    </PageLayout>
  );
}
