"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { SupportTicketReplyDialog } from "@/components/support-ticket-reply-dialog";
import {
  useSupportTickets,
  useSupportTicketStats,
} from "@/hooks/use-support-tickets";
import {
  SupportTicket,
  SupportTicketStatus,
  SupportTicketType,
  SupportTicketParams,
} from "@/types/api";
import {
  Search,
  Filter,
  RefreshCw,
  MessageSquare,
  User,
  Mail,
  Calendar,
  Tag,
  ChevronLeft,
  ChevronRight,
  AlertCircle,
  Bug,
  HelpCircle,
  UserCheck,
  Loader2,
} from "lucide-react";
// import { formatDistanceToNow } from 'date-fns';

export default function SupportTicketsPage() {
  const [filters, setFilters] = useState<SupportTicketParams>({
    page: 1,
    limit: 10,
    type: "all",
    status: "all",
    search: "",
  });

  const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(
    null
  );
  const [isReplyDialogOpen, setIsReplyDialogOpen] = useState(false);

  const {
    data: ticketsData,
    isLoading: ticketsLoading,
    error: ticketsError,
  } = useSupportTickets(filters);
  const { data: statsData, isLoading: statsLoading } = useSupportTicketStats();

  const tickets =
    (
      ticketsData?.data as {
        data: { supportTickets: { supportTickets: SupportTicket[] } };
      }
    )?.data?.supportTickets?.supportTickets || [];
  const pagination =
    (
      ticketsData?.data as {
        data: {
          supportTickets: {
            totalDocs: number;
            currentPage: number;
            totalPages: number;
            hasNextPage: boolean;
            hasPrevPage: boolean;
          };
        };
      }
    )?.data?.supportTickets || null;

  const handleFilterChange = (
    key: keyof SupportTicketParams,
    value: string | number
  ) => {
    setFilters((prev) => ({
      ...prev,
      [key]: value,
      page: 1, // Reset to first page when filters change
    }));
  };

  const handleSearch = (searchTerm: string) => {
    setFilters((prev) => ({
      ...prev,
      search: searchTerm,
      page: 1,
    }));
  };

  const handlePageChange = (page: number) => {
    setFilters((prev) => ({
      ...prev,
      page,
    }));
  };

  const handleReply = (ticket: SupportTicket) => {
    setSelectedTicket(ticket);
    setIsReplyDialogOpen(true);
  };

  const getStatusColor = (status: SupportTicketStatus) => {
    switch (status) {
      case "open":
        return "bg-red-100 text-red-800 border-red-200";
      case "in_progress":
        return "bg-yellow-100 text-yellow-800 border-yellow-200";
      case "closed":
        return "bg-green-100 text-green-800 border-green-200";
      default:
        return "bg-gray-100 text-gray-800 border-gray-200";
    }
  };

  const getTypeColor = (type: SupportTicketType) => {
    switch (type) {
      case "bug":
        return "bg-red-100 text-red-800";
      case "account_recovery":
        return "bg-orange-100 text-orange-800";
      case "other":
        return "bg-blue-100 text-blue-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  const getTypeIcon = (type: SupportTicketType) => {
    switch (type) {
      case "bug":
        return <Bug className="h-4 w-4" />;
      case "account_recovery":
        return <UserCheck className="h-4 w-4" />;
      case "other":
        return <HelpCircle className="h-4 w-4" />;
      default:
        return <MessageSquare className="h-4 w-4" />;
    }
  };

  const stats = statsData?.data || {
    total: 0,
    open: 0,
    inProgress: 0,
    closed: 0,
    byType: { bug: 0, other: 0, account_recovery: 0 },
  };

  if (ticketsError) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            Error Loading Tickets
          </h3>
          <p className=" mb-4">
            There was an error loading the support tickets.
          </p>
          <Button onClick={() => window.location.reload()}>
            <RefreshCw className="mr-2 h-4 w-4" />
            Try Again
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Support Tickets</h1>
          <p className="text-muted-foreground">
            Manage and respond to user support requests
          </p>
        </div>
        {/* <Button
          onClick={() => window.location.reload()}
          variant="outline"
          size="sm"
        >
          <RefreshCw className="mr-2 h-4 w-4" />
          Refresh
        </Button> */}
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Tickets</CardTitle>
            <MessageSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            {statsLoading ? (
              <Skeleton className="h-8 w-16" />
            ) : (
              <div className="text-2xl font-bold">{stats.total}</div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Open</CardTitle>
            <AlertCircle className="h-4 w-4 text-red-500" />
          </CardHeader>
          <CardContent>
            {statsLoading ? (
              <Skeleton className="h-8 w-16" />
            ) : (
              <div className="text-2xl font-bold text-red-600">
                {stats.open}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">In Progress</CardTitle>
            <Loader2 className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            {statsLoading ? (
              <Skeleton className="h-8 w-16" />
            ) : (
              <div className="text-2xl font-bold text-yellow-600">
                {stats.inProgress}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Closed</CardTitle>
            <UserCheck className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            {statsLoading ? (
              <Skeleton className="h-8 w-16" />
            ) : (
              <div className="text-2xl font-bold text-green-600">
                {stats.closed}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-5 w-5" />
            Filters
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* <div className="space-y-2">
              <Label htmlFor="search">Search</Label>
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Search tickets..."
                  value={filters.search || ""}
                  onChange={(e) => handleSearch(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div> */}

            <div className="space-y-2">
              <Label htmlFor="type">Type</Label>
              <Select
                value={filters.type || "all"}
                onValueChange={(value) => handleFilterChange("type", value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  <SelectItem value="bug">Bug Report</SelectItem>
                  <SelectItem value="account_recovery">
                    Account Recovery
                  </SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select
                value={filters.status || "all"}
                onValueChange={(value) => handleFilterChange("status", value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Statuses</SelectItem>
                  <SelectItem value="open">Open</SelectItem>
                  <SelectItem value="in_progress">In Progress</SelectItem>
                  <SelectItem value="closed">Closed</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="limit">Per Page</Label>
              <Select
                value={filters.limit?.toString() || "10"}
                onValueChange={(value) =>
                  handleFilterChange("limit", parseInt(value))
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">10</SelectItem>
                  <SelectItem value="20">20</SelectItem>
                  <SelectItem value="50">50</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tickets List */}
      <Card>
        <CardHeader>
          <CardTitle>Tickets</CardTitle>
          <CardDescription>
            {pagination
              ? `${pagination.totalDocs} total tickets`
              : "Loading..."}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {ticketsLoading ? (
            <div className="space-y-4">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <Skeleton className="h-6 w-48" />
                    <Skeleton className="h-6 w-20" />
                  </div>
                  <Skeleton className="h-4 w-96 mb-2" />
                  <Skeleton className="h-4 w-64" />
                </div>
              ))}
            </div>
          ) : tickets.length === 0 ? (
            <div className="text-center py-8">
              <MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-gray-900 mb-2">
                No tickets found
              </h3>
              <p className="">
                {filters.search ||
                filters.type !== "all" ||
                filters.status !== "all"
                  ? "No tickets match your current filters."
                  : "No support tickets have been submitted yet."}
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {tickets.map((ticket: SupportTicket) => (
                <div
                  key={ticket._id}
                  className="border rounded-lg p-4  transition-colors"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <div className="flex items-center gap-2">
                        {getTypeIcon(ticket.type)}
                        <Badge className={getTypeColor(ticket.type)}>
                          {ticket.type.replace("_", " ").toUpperCase()}
                        </Badge>
                      </div>
                      <Badge className={getStatusColor(ticket.status)}>
                        {ticket.status.replace("_", " ").toUpperCase()}
                      </Badge>
                    </div>
                    <Button
                      size="sm"
                      onClick={() => handleReply(ticket)}
                      disabled={ticket.status === "closed"}
                    >
                      <MessageSquare className="mr-2 h-4 w-4" />
                      Reply
                    </Button>
                  </div>

                  <div className="space-y-2">
                    <h3 className="font-semibold text-lg">{ticket.subject}</h3>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm ">
                      {/* <div className="flex items-center gap-2">
                        <User className="h-4 w-4" />
                        <span className="font-medium">User:</span>
                        <span>{ticket.user.fullName}</span>
                      </div> */}
                      <div className="flex items-center gap-2">
                        <Mail className="h-4 w-4" />
                        <span className="font-medium">Email:</span>
                        <span>{ticket.user.email}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4" />
                        <span className="font-medium">Created:</span>
                        <span>
                          {new Date(ticket.createdAt).toLocaleDateString()}
                        </span>
                      </div>
                      {ticket.user.originalEmail && (
                        <div className="flex items-center gap-2">
                          <Tag className="h-4 w-4" />
                          <span className="font-medium">Original Email:</span>
                          <span>{ticket.user.originalEmail}</span>
                        </div>
                      )}
                    </div>

                    <div className="mt-3">
                      <p className=" whitespace-pre-wrap">
                        {ticket.description}
                      </p>
                    </div>

                    {ticket.response && (
                      <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                        <h4 className="font-medium text-blue-900 mb-1">
                          Admin Response:
                        </h4>
                        <p className="text-blue-800 text-sm whitespace-pre-wrap">
                          {ticket.response}
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Pagination */}
          {pagination && pagination.totalPages > 1 && (
            <div className="flex items-center justify-between mt-6">
              <div className="text-sm ">
                Showing{" "}
                {(pagination.currentPage - 1) * (filters.limit || 10) + 1} to{" "}
                {Math.min(
                  pagination.currentPage * (filters.limit || 10),
                  pagination.totalDocs
                )}{" "}
                of {pagination.totalDocs} results
              </div>

              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(pagination.currentPage - 1)}
                  disabled={!pagination.hasPrevPage}
                >
                  <ChevronLeft className="h-4 w-4" />
                  Previous
                </Button>

                <div className="flex items-center gap-1">
                  {(() => {
                    const currentPage = pagination.currentPage;
                    const totalPages = pagination.totalPages;
                    const maxVisiblePages = 5;

                    let startPage = Math.max(
                      1,
                      currentPage - Math.floor(maxVisiblePages / 2)
                    );
                    const endPage = Math.min(
                      totalPages,
                      startPage + maxVisiblePages - 1
                    );

                    // Adjust start page if we're near the end
                    if (endPage - startPage + 1 < maxVisiblePages) {
                      startPage = Math.max(1, endPage - maxVisiblePages + 1);
                    }

                    const pages = [];
                    for (let i = startPage; i <= endPage; i++) {
                      pages.push(
                        <Button
                          key={i}
                          variant={i === currentPage ? "default" : "outline"}
                          size="sm"
                          onClick={() => handlePageChange(i)}
                          className="w-8 h-8 p-0"
                        >
                          {i}
                        </Button>
                      );
                    }
                    return pages;
                  })()}
                </div>

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(pagination.currentPage + 1)}
                  disabled={!pagination.hasNextPage}
                >
                  Next
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Reply Dialog */}
      <SupportTicketReplyDialog
        ticket={selectedTicket}
        isOpen={isReplyDialogOpen}
        onClose={() => {
          setIsReplyDialogOpen(false);
          setSelectedTicket(null);
        }}
      />
    </div>
  );
}
