"use client";

import { useDeferredValue, useMemo, useState } from "react";
import Link from "next/link";
import {
  ChatBubbleLeftRightIcon,
  MagnifyingGlassIcon,
  PlusIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  ChevronRightIcon,
  CalendarIcon,
  UserIcon,
} from "@heroicons/react/24/outline";
import { format } from "date-fns";
import { useSupportCases } from "@/features/support/hooks/useSupportCases";
import {
  SUPPORT_CASE_PRIORITY,
  SUPPORT_CASE_STATUS,
  type SupportCaseFilter,
  type SupportCasePriority,
  type SupportCaseStatus,
} from "@customer-portal/domain/support";

export function SupportCasesView() {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<SupportCaseStatus | "all">("all");
  const [priorityFilter, setPriorityFilter] = useState<SupportCasePriority | "all">("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, isLoading, error } = useSupportCases(queryFilters);
  const cases = data?.cases ?? [];
  const summary = data?.summary ?? { total: 0, open: 0, highPriority: 0, resolved: 0 };

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

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

  const getStatusIcon = (status: SupportCaseStatus) => {
    switch (status) {
      case SUPPORT_CASE_STATUS.RESOLVED:
      case SUPPORT_CASE_STATUS.CLOSED:
        return <CheckCircleIcon className="h-5 w-5 text-green-500" />;
      case SUPPORT_CASE_STATUS.IN_PROGRESS:
        return <ClockIcon className="h-5 w-5 text-blue-500" />;
      case SUPPORT_CASE_STATUS.WAITING_ON_CUSTOMER:
        return <ExclamationTriangleIcon className="h-5 w-5 text-yellow-500" />;
      case SUPPORT_CASE_STATUS.OPEN:
        return <ChatBubbleLeftRightIcon className="h-5 w-5 text-gray-500" />;
      default:
        return <ChatBubbleLeftRightIcon className="h-5 w-5 text-gray-500" />;
    }
  };

  const getStatusColor = (status: SupportCaseStatus) => {
    switch (status) {
      case SUPPORT_CASE_STATUS.RESOLVED:
      case SUPPORT_CASE_STATUS.CLOSED:
        return "bg-green-100 text-green-800";
      case SUPPORT_CASE_STATUS.IN_PROGRESS:
        return "bg-blue-100 text-blue-800";
      case SUPPORT_CASE_STATUS.WAITING_ON_CUSTOMER:
        return "bg-yellow-100 text-yellow-800";
      case SUPPORT_CASE_STATUS.OPEN:
        return "bg-gray-100 text-gray-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  const getPriorityColor = (priority: SupportCasePriority) => {
    switch (priority) {
      case SUPPORT_CASE_PRIORITY.CRITICAL:
        return "bg-red-100 text-red-800";
      case SUPPORT_CASE_PRIORITY.HIGH:
        return "bg-orange-100 text-orange-800";
      case SUPPORT_CASE_PRIORITY.MEDIUM:
        return "bg-yellow-100 text-yellow-800";
      case SUPPORT_CASE_PRIORITY.LOW:
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading support cases...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="py-6">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 md:px-8">
          {/* Header */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">Support Cases</h1>
                <p className="mt-1 text-sm text-gray-600">Track and manage your support requests</p>
              </div>
              <Link
                href="/support/new"
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
              >
                <PlusIcon className="h-4 w-4 mr-2" />
                New Case
              </Link>
            </div>
          </div>

          {error && (
            <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-800">
              {error instanceof Error ? error.message : "Failed to load support cases"}
            </div>
          )}

          {/* Stats Cards */}
          <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-8">
            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <ChatBubbleLeftRightIcon className="h-6 w-6 text-gray-600" />
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">Total Cases</dt>
                      <dd className="text-lg font-medium text-gray-900">{summary.total}</dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <ClockIcon className="h-6 w-6 text-blue-600" />
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">Open Cases</dt>
                      <dd className="text-lg font-medium text-gray-900">{summary.open}</dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <ExclamationTriangleIcon className="h-6 w-6 text-red-600" />
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">High Priority</dt>
                      <dd className="text-lg font-medium text-gray-900">{summary.highPriority}</dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <CheckCircleIcon className="h-6 w-6 text-green-600" />
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">Resolved</dt>
                      <dd className="text-lg font-medium text-gray-900">{summary.resolved}</dd>
                    </dl>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Filters */}
          <div className="bg-white shadow rounded-lg mb-6">
            <div className="p-6">
              <div className="flex flex-col sm:flex-row gap-4">
                {/* Search */}
                <div className="flex-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
                  </div>
                  <input
                    type="text"
                    placeholder="Search cases..."
                    value={searchTerm}
                    onChange={event => setSearchTerm(event.target.value)}
                    className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                {/* Status Filter */}
                <div className="relative">
                  <select
                    value={statusFilter}
                    onChange={event =>
                      setStatusFilter(event.target.value as SupportCaseStatus | "all")
                    }
                    className="block w-full px-3 py-2 border border-gray-300 rounded-md leading-5 bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  >
                    {statusFilterOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Priority Filter */}
                <div className="relative">
                  <select
                    value={priorityFilter}
                    onChange={event =>
                      setPriorityFilter(event.target.value as SupportCasePriority | "all")
                    }
                    className="block w-full px-3 py-2 border border-gray-300 rounded-md leading-5 bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                  >
                    {priorityFilterOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* Cases List */}
          <div className="bg-white shadow overflow-hidden sm:rounded-md">
            <ul className="divide-y divide-gray-200">
              {cases.map(supportCase => (
                <li key={supportCase.id}>
                  <Link
                    href={`/support/cases/${supportCase.id}`}
                    className="block hover:bg-gray-50"
                  >
                    <div className="px-4 py-4 sm:px-6">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4 flex-1">
                          <div className="flex-shrink-0">{getStatusIcon(supportCase.status)}</div>
                          <div className="min-w-0 flex-1">
                            <div className="flex items-center space-x-3 mb-2">
                              <p className="text-sm font-medium text-blue-600 truncate">
                                #{supportCase.id} - {supportCase.subject}
                              </p>
                              <span
                                className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(supportCase.status)}`}
                              >
                                {supportCase.status}
                              </span>
                              <span
                                className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getPriorityColor(supportCase.priority)}`}
                              >
                                {supportCase.priority}
                              </span>
                            </div>
                            <p className="text-sm text-gray-500 mb-2 line-clamp-2">
                              {supportCase.description}
                            </p>
                            <div className="flex items-center space-x-6 text-xs text-gray-500">
                              <div className="flex items-center">
                                <CalendarIcon className="h-4 w-4 mr-1" />
                                Created: {format(new Date(supportCase.createdAt), "MMM d, yyyy")}
                              </div>
                              <div className="flex items-center">
                                <CalendarIcon className="h-4 w-4 mr-1" />
                                Updated: {format(new Date(supportCase.updatedAt), "MMM d, yyyy")}
                              </div>
                              {supportCase.assignedTo && (
                                <div className="flex items-center">
                                  <UserIcon className="h-4 w-4 mr-1" />
                                  {supportCase.assignedTo}
                                </div>
                              )}
                              <span className="capitalize bg-gray-100 text-gray-700 px-2 py-1 rounded text-xs">
                                {supportCase.category}
                              </span>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <ChevronRightIcon className="h-5 w-5 text-gray-400" />
                        </div>
                      </div>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>

            {/* Empty State */}
            {cases.length === 0 && (
              <div className="text-center py-12">
                <ChatBubbleLeftRightIcon className="mx-auto h-12 w-12 text-gray-400" />
                <h3 className="mt-2 text-sm font-medium text-gray-900">No support cases found</h3>
                <p className="mt-1 text-sm text-gray-500">
                  {searchTerm || statusFilter !== "all" || priorityFilter !== "all"
                    ? "Try adjusting your search or filter criteria"
                    : "Your support cases will appear here when you create them"}
                </p>
                {searchTerm === "" && statusFilter === "all" && priorityFilter === "all" && (
                  <div className="mt-6">
                    <Link
                      href="/support/new"
                      className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
                    >
                      <PlusIcon className="h-4 w-4 mr-2" />
                      Create Your First Case
                    </Link>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
