"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  SparklesIcon,
  PlusIcon,
  ChevronRightIcon,
  TicketIcon,
  ClockIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import { ChatBubbleLeftRightIcon as ChatBubbleLeftRightIconSolid } from "@heroicons/react/24/solid";
import { PageLayout } from "@/components/templates/PageLayout";
import { AnimatedCard } from "@/components/molecules";
import { Button } from "@/components/atoms";
import { EmptyState } from "@/components/atoms/empty-state";
import { useSupportCases } from "@/features/support/hooks/useSupportCases";
import { getCaseStatusIcon, getCaseStatusClasses } from "@/features/support/utils";
import { formatIsoRelative } from "@/shared/utils";

function CaseListItem({
  supportCase,
  onClick,
}: {
  supportCase: {
    id: string;
    caseNumber: string;
    status: string;
    subject: string;
    updatedAt: string;
  };
  onClick: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className="flex items-center gap-4 p-4 hover:bg-muted cursor-pointer transition-colors group"
    >
      <div className="flex-shrink-0">{getCaseStatusIcon(supportCase.status)}</div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-0.5">
          <span className="text-sm font-medium text-foreground">#{supportCase.caseNumber}</span>
          <span
            className={`text-xs px-1.5 py-0.5 rounded font-medium ${getCaseStatusClasses(supportCase.status)}`}
          >
            {supportCase.status}
          </span>
        </div>
        <p className="text-sm text-muted-foreground truncate">{supportCase.subject}</p>
      </div>
      <div className="hidden sm:block text-xs text-muted-foreground/70 flex-shrink-0">
        {formatIsoRelative(supportCase.updatedAt)}
      </div>
      <ChevronRightIcon className="h-4 w-4 text-muted-foreground/60 group-hover:text-muted-foreground flex-shrink-0 transition-colors" />
    </div>
  );
}

function QuickActions() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
      <div className="bg-card text-card-foreground rounded-xl p-5 border border-border shadow-[var(--cp-shadow-1)]">
        <div className="flex items-start gap-4">
          <div className="w-10 h-10 bg-muted rounded-lg flex items-center justify-center flex-shrink-0">
            <SparklesIcon className="h-5 w-5 text-primary" />
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold mb-1 text-foreground">AI Assistant</h3>
            <p className="text-sm text-muted-foreground mb-4 leading-relaxed">
              Get instant answers to common questions about your account.
            </p>
            <Button size="sm" variant="secondary">
              Start Chat
            </Button>
          </div>
        </div>
      </div>
      <div className="border border-border rounded-xl p-5 bg-card text-card-foreground shadow-[var(--cp-shadow-1)]">
        <div className="flex items-start gap-4">
          <div className="w-10 h-10 bg-muted rounded-lg flex items-center justify-center flex-shrink-0">
            <PlusIcon className="h-5 w-5 text-muted-foreground" />
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold text-foreground mb-1">Create Support Case</h3>
            <p className="text-sm text-muted-foreground mb-4 leading-relaxed">
              Our team typically responds within 24 hours.
            </p>
            <Button as="a" href="/account/support/new" size="sm" variant="outline">
              New Case
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

export function SupportHomeView() {
  const router = useRouter();
  const { data, error, refetch } = useSupportCases();
  const recentCases = data?.cases?.slice(0, 5) ?? [];
  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;

  return (
    <PageLayout
      icon={<ChatBubbleLeftRightIconSolid />}
      title="Support Center"
      loading={showLoading}
      error={error}
      onRetry={() => void refetch()}
    >
      <QuickActions />

      {/* Cases Section */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-4">
            <h3 className="text-lg font-semibold text-foreground">Your Cases</h3>
            {summary.total > 0 && (
              <div className="flex items-center gap-3 text-sm">
                <span className="flex items-center gap-1.5 text-muted-foreground">
                  <ClockIcon className="h-4 w-4 text-primary" />
                  <span className="font-medium text-primary">{summary.open}</span> open
                </span>
                <span className="flex items-center gap-1.5 text-muted-foreground">
                  <CheckCircleIcon className="h-4 w-4 text-success" />
                  <span className="font-medium text-success">{summary.resolved}</span> resolved
                </span>
              </div>
            )}
          </div>
          {summary.total > 0 && (
            <Link
              href="/account/support"
              className="text-sm text-primary hover:underline font-medium inline-flex items-center gap-1"
            >
              View all
              <ChevronRightIcon className="h-4 w-4" />
            </Link>
          )}
        </div>

        {recentCases.length > 0 ? (
          <div className="border border-border rounded-xl bg-card divide-y divide-border overflow-hidden shadow-[var(--cp-shadow-1)]">
            {recentCases.map(supportCase => (
              <CaseListItem
                key={supportCase.id}
                supportCase={supportCase}
                onClick={() => router.push(`/account/support/${supportCase.id}`)}
              />
            ))}
          </div>
        ) : (
          <AnimatedCard className="p-8" variant="static">
            <EmptyState
              icon={<TicketIcon className="h-12 w-12" />}
              title="No support cases yet"
              description="Need help? Start a chat with our AI assistant or create a support case."
              action={{
                label: "Create Case",
                onClick: () => router.push("/account/support/new"),
              }}
            />
          </AnimatedCard>
        )}
      </div>
    </PageLayout>
  );
}
