"use client";

import { useState } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Download,
  Users,
  UserCheck,
  UserX,
  Search,
  ChevronLeft,
  ChevronRight,
  Mail,
  Calendar,
} from "lucide-react";
import { useWaitlist, useExportWaitlistCsv } from "@/hooks";
import { WaitlistParams } from "@/types/api";

export default function WaitlistPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  const [onboardingFilter, setOnboardingFilter] = useState<string>("all");

  // Build query parameters
  const queryParams: WaitlistParams = {
    page: currentPage,
    limit,
    isOnBoarded:
      onboardingFilter === "all" ? undefined : onboardingFilter === "onboarded",
  };

  // Fetch waitlist data
  const { data: waitlistData, isLoading, error } = useWaitlist(queryParams);

  // Export CSV mutation
  const exportCsvMutation = useExportWaitlistCsv();

  // Filter waitlist entries based on search term
  const waitlistEntries =
    (
      waitlistData?.data?.waitlist as {
        waitlist: {
          email: string;
          name?: string;
          isOnBoarded: boolean;
          _id: string;
          createdAt: string;
        }[];
      }
    )?.waitlist || [];
  const filteredWaitlist = waitlistEntries.filter(
    (entry: { email: string; name?: string }) => {
      if (!searchTerm) return true;
      const searchLower = searchTerm.toLowerCase();
      return (
        entry.email.toLowerCase().includes(searchLower) ||
        (entry.name && entry.name.toLowerCase().includes(searchLower))
      );
    }
  );

  // Pagination handlers
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleLimitChange = (newLimit: string) => {
    setLimit(parseInt(newLimit));
    setCurrentPage(1); // Reset to first page when changing limit
  };

  // Export handlers
  const handleExportAll = () => {
    exportCsvMutation.mutate(undefined);
  };

  const handleExportOnboarded = () => {
    exportCsvMutation.mutate(true);
  };

  const handleExportWaiting = () => {
    exportCsvMutation.mutate(false);
  };

  // Format date
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // Get status color
  const getStatusColor = (isOnBoarded: boolean) => {
    return isOnBoarded
      ? "bg-green-100 text-green-800"
      : "bg-yellow-100 text-yellow-800";
  };

  const pagination = waitlistData?.data?.waitlist as {
    totalDocs: number;
    currentPage: number;
    totalPages: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };

  return (
    <div className="flex-1 space-y-6 p-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">
            Waitlist Management
          </h1>
          <p className="text-muted-foreground">
            Manage and monitor platform waitlist entries
          </p>
        </div>
      </div>

      {/* Stats Cards */}
      {/* <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Entries</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {pagination?.totalDocs || 0}
            </div>
            <p className="text-xs text-muted-foreground">
              {pagination?.currentPage || 1} of {pagination?.totalPages || 1}{" "}
              pages
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Onboarded</CardTitle>
            <UserCheck className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
             <div className="text-2xl font-bold">
               {waitlistEntries.filter(
                 (entry) => entry.isOnBoarded
               ).length || 0}
             </div>
            <p className="text-xs text-muted-foreground">
              Successfully onboarded
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Waiting</CardTitle>
            <UserX className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
             <div className="text-2xl font-bold">
               {waitlistEntries.filter(
                 (entry) => !entry.isOnBoarded
               ).length || 0}
             </div>
            <p className="text-xs text-muted-foreground">Still waiting</p>
          </CardContent>
        </Card>
      </div> */}

      {/* Filters and Actions */}
      <Card>
        <CardHeader>
          <CardTitle>
            Waitlist Entries
            <h1 className="font-light text-sm mt-2">
              Total Users in waitlist {pagination?.totalDocs || 0}
            </h1>
          </CardTitle>
          <CardDescription>
            View and manage waitlist entries with filtering and export options
          </CardDescription>
        </CardHeader>
        <CardContent>
          {/* Filters */}
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <div className="flex-1">
              <Label htmlFor="search">Search</Label>
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Search by their email ..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>
            <div className="sm:w-48">
              <Label htmlFor="filter">Status Filter</Label>
              <Select
                value={onboardingFilter}
                onValueChange={setOnboardingFilter}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Filter by status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Entries</SelectItem>
                  <SelectItem value="onboarded">Onboarded</SelectItem>
                  <SelectItem value="waiting">Waiting</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="sm:w-32">
              <Label htmlFor="limit">Per Page</Label>
              <Select
                value={limit.toString()}
                onValueChange={handleLimitChange}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="10">10</SelectItem>
                  <SelectItem value="20">20</SelectItem>
                  <SelectItem value="50">50</SelectItem>
                  <SelectItem value="100">100</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Export Actions */}
          <div className="flex flex-wrap gap-2 mb-6">
            <Button
              onClick={handleExportAll}
              disabled={exportCsvMutation.isPending}
              className="gradient-button"
            >
              <Download className="h-4 w-4 mr-2" />
              Export All CSV
            </Button>
            <Button
              onClick={handleExportOnboarded}
              disabled={exportCsvMutation.isPending}
              variant="outline"
              className="gradient-button"
            >
              <UserCheck className="h-4 w-4 mr-2" />
              Export Onboarded
            </Button>
            <Button
              onClick={handleExportWaiting}
              disabled={exportCsvMutation.isPending}
              variant="outline"
              className="gradient-button"
            >
              <UserX className="h-4 w-4 mr-2" />
              Export Waiting
            </Button>
          </div>

          {/* Waitlist Entries */}
          {isLoading ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div
                  key={i}
                  className="flex items-center justify-between p-4 border rounded-lg animate-pulse"
                >
                  <div className="flex items-center space-x-3">
                    <div className="h-10 w-10 bg-gray-200 rounded-full"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded w-32"></div>
                      <div className="h-3 bg-gray-200 rounded w-24"></div>
                    </div>
                  </div>
                  <div className="flex space-x-2">
                    <div className="h-6 w-16 bg-gray-200 rounded"></div>
                    <div className="h-6 w-20 bg-gray-200 rounded"></div>
                  </div>
                </div>
              ))}
            </div>
          ) : error ? (
            <div className="text-center py-8">
              <div className="text-red-500">
                <UserX className="h-12 w-12 mx-auto mb-4" />
                <p className="text-lg font-medium">Failed to load waitlist</p>
                <p className="text-sm">Please try again later</p>
              </div>
            </div>
          ) : filteredWaitlist.length === 0 ? (
            <div className="text-center py-8">
              <div className="text-muted-foreground">
                <Users className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p className="text-lg font-medium">No waitlist entries found</p>
                <p className="text-sm">
                  {searchTerm
                    ? "Try adjusting your search terms"
                    : "No entries match your current filters"}
                </p>
              </div>
            </div>
          ) : (
            <div className="space-y-3">
              {filteredWaitlist.map(
                (entry: {
                  _id: string;
                  email: string;
                  name?: string;
                  isOnBoarded: boolean;
                  createdAt: string;
                }) => (
                  <div
                    key={entry._id}
                    className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-center space-x-3">
                      {/* <div className="h-10 w-10 bg-gradient-to-r from-[#ee6285] to-[#bb56d2] rounded-full flex items-center justify-center">
                      <span className="text-white font-medium text-sm">
                        {entry.name.charAt(0).toUpperCase()}
                      </span>
                    </div> */}
                      <div>
                        <h4 className="font-medium">
                          {entry.name || entry.email}
                        </h4>
                        <p className="text-sm text-muted-foreground flex items-center">
                          <Mail className="h-3 w-3 mr-1" />
                          {entry.email}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <div className="text-right">
                        <p className="text-xs text-muted-foreground flex items-center">
                          <Calendar className="h-3 w-3 mr-1" />
                          {formatDate(entry.createdAt)}
                        </p>
                      </div>
                      <Badge
                        className={`${getStatusColor(
                          entry.isOnBoarded
                        )} capitalize`}
                      >
                        {entry.isOnBoarded ? "Onboarded" : "Waiting"}
                      </Badge>
                    </div>
                  </div>
                )
              )}
            </div>
          )}

          {/* Pagination */}
          {pagination && pagination.totalPages > 1 && (
            <div className="flex items-center justify-between mt-6">
              <div className="text-sm text-muted-foreground">
                Showing {(currentPage - 1) * limit + 1} to{" "}
                {Math.min(currentPage * limit, pagination.totalDocs)} of{" "}
                {pagination.totalDocs} entries
              </div>
              <div className="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={!pagination.hasPrevPage}
                  className="gradient-button"
                >
                  <ChevronLeft className="h-4 w-4" />
                  Previous
                </Button>
                <div className="flex items-center space-x-1">
                  {Array.from(
                    { length: Math.min(5, pagination.totalPages) },
                    (_, i) => {
                      const pageNum = i + 1;
                      return (
                        <Button
                          key={pageNum}
                          variant={
                            currentPage === pageNum ? "default" : "outline"
                          }
                          size="sm"
                          onClick={() => handlePageChange(pageNum)}
                          className={
                            currentPage === pageNum
                              ? "gradient-button"
                              : "gradient-button"
                          }
                        >
                          {pageNum}
                        </Button>
                      );
                    }
                  )}
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={!pagination.hasNextPage}
                  className="gradient-button"
                >
                  Next
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
