"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { ClientTable } from "@/components/clients/client-table";
import { ClientForm } from "@/components/clients/client-form";
import { ClientDetailDialog } from "@/components/clients/client-detail-dialog";
import { AssignMembershipDialog } from "@/components/memberships/assign-membership-dialog";
import { StatCard, StatCardSkeleton } from "@/components/dashboard/stat-card";

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email: string | null;
  phone: string | null;
  avatar?: string | null;
  level: string | null;
  notes: string | null;
  isActive: boolean;
  createdAt: string;
  memberships?: Array<{
    id: string;
    status: string;
    startDate: string;
    endDate: string;
    remainingHours: number | null;
    plan: {
      id: string;
      name: string;
      price: number | string;
      durationMonths: number;
      courtHours: number | null;
      discountPercent: number | string | null;
    };
  }>;
  _count?: {
    bookings: number;
  };
  stats?: {
    totalBookings: number;
    totalSpent: number;
    balance: number;
  };
}

interface ClientsResponse {
  data: Client[];
  pagination: {
    total: number;
    limit: number;
    offset: number;
    hasMore: boolean;
  };
}

interface MembershipPlan {
  id: string;
  name: string;
  price: number | string;
  durationMonths: number;
  courtHours: number | null;
  discountPercent: number | string | null;
}

const membershipFilters = [
  { value: "", label: "All" },
  { value: "with", label: "With membership" },
  { value: "without", label: "Without membership" },
];

const ITEMS_PER_PAGE = 10;

export default function ClientsPage() {
  // Clients state
  const [clients, setClients] = useState<Client[]>([]);
  const [loadingClients, setLoadingClients] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [membershipFilter, setMembershipFilter] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalClients, setTotalClients] = useState(0);

  // Modal state
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [showAssignMembership, setShowAssignMembership] = useState(false);
  const [formLoading, setFormLoading] = useState(false);

  // Stats state
  const [stats, setStats] = useState({
    totalClients: 0,
    withMembership: 0,
    newThisMonth: 0,
  });
  const [loadingStats, setLoadingStats] = useState(true);

  // Membership plans for assignment dialog
  const [membershipPlans, setMembershipPlans] = useState<MembershipPlan[]>([]);

  const [error, setError] = useState<string | null>(null);

  // Fetch clients
  const fetchClients = useCallback(async () => {
    setLoadingClients(true);
    try {
      const params = new URLSearchParams();
      if (searchQuery) params.append("search", searchQuery);
      params.append("limit", ITEMS_PER_PAGE.toString());
      params.append("offset", ((currentPage - 1) * ITEMS_PER_PAGE).toString());

      const response = await fetch(`/api/clients?${params.toString()}`);
      if (!response.ok) throw new Error("Error loading players");

      const data: ClientsResponse = await response.json();

      // Filter by membership status client-side for simplicity
      let filteredData = data.data;
      if (membershipFilter === "with") {
        filteredData = data.data.filter(
          (c) =>
            c.memberships &&
            c.memberships.length > 0 &&
            c.memberships[0].status === "ACTIVE"
        );
      } else if (membershipFilter === "without") {
        filteredData = data.data.filter(
          (c) =>
            !c.memberships ||
            c.memberships.length === 0 ||
            c.memberships[0].status !== "ACTIVE"
        );
      }

      setClients(filteredData);
      setTotalClients(data.pagination.total);
    } catch (err) {
      console.error("Error fetching clients:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoadingClients(false);
    }
  }, [searchQuery, currentPage, membershipFilter]);

  // Fetch stats
  const fetchStats = useCallback(async () => {
    setLoadingStats(true);
    try {
      // Fetch all clients to calculate stats
      const response = await fetch("/api/clients?limit=1000");
      if (!response.ok) throw new Error("Error loading statistics");

      const data: ClientsResponse = await response.json();
      const allClients = data.data;

      // Calculate stats
      const now = new Date();
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

      const withMembership = allClients.filter(
        (c) =>
          c.memberships &&
          c.memberships.length > 0 &&
          c.memberships[0].status === "ACTIVE"
      ).length;

      const newThisMonth = allClients.filter(
        (c) => new Date(c.createdAt) >= startOfMonth
      ).length;

      setStats({
        totalClients: data.pagination.total,
        withMembership,
        newThisMonth,
      });
    } catch (err) {
      console.error("Error fetching stats:", err);
    } finally {
      setLoadingStats(false);
    }
  }, []);

  // Fetch membership plans
  const fetchMembershipPlans = useCallback(async () => {
    try {
      const response = await fetch("/api/membership-plans");
      if (!response.ok) throw new Error("Error loading plans");
      const data = await response.json();
      setMembershipPlans(data.filter((p: MembershipPlan & { isActive?: boolean }) => p.isActive !== false));
    } catch (err) {
      console.error("Error fetching membership plans:", err);
    }
  }, []);

  // Fetch client details
  const fetchClientDetails = async (clientId: string) => {
    try {
      const response = await fetch(`/api/clients/${clientId}`);
      if (!response.ok) throw new Error("Error loading player details");
      const data = await response.json();
      setSelectedClient(data);
    } catch (err) {
      console.error("Error fetching client details:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  useEffect(() => {
    fetchClients();
    fetchStats();
    fetchMembershipPlans();
  }, [fetchClients, fetchStats, fetchMembershipPlans]);

  // Debounce search
  const [debouncedSearch, setDebouncedSearch] = useState(searchQuery);
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearch, membershipFilter]);

  // Handle create client
  const handleCreateClient = async (data: {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    avatar?: string;
  }) => {
    setFormLoading(true);
    try {
      const response = await fetch("/api/clients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error creating player");
      }

      setShowCreateForm(false);
      await Promise.all([fetchClients(), fetchStats()]);
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  // Handle update client
  const handleUpdateClient = async (data: {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    avatar?: string;
  }) => {
    if (!editingClient) return;

    setFormLoading(true);
    try {
      const response = await fetch(`/api/clients/${editingClient.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error updating player");
      }

      setEditingClient(null);
      await fetchClients();

      // Update selected client if viewing details
      if (selectedClient?.id === editingClient.id) {
        await fetchClientDetails(editingClient.id);
      }
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  // Handle delete client
  const handleDeleteClient = async (client: Client) => {
    if (
      !confirm(
        `Are you sure you want to deactivate ${client.firstName} ${client.lastName}?`
      )
    ) {
      return;
    }

    try {
      const response = await fetch(`/api/clients/${client.id}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error deactivating player");
      }

      await Promise.all([fetchClients(), fetchStats()]);
    } catch (err) {
      console.error("Error deleting client:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  // Handle assign membership
  const handleAssignMembership = async (data: {
    clientId: string;
    planId: string;
    startDate: string;
    endDate: string;
  }) => {
    setFormLoading(true);
    try {
      const response = await fetch("/api/memberships", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error assigning membership");
      }

      setShowAssignMembership(false);
      await Promise.all([fetchClients(), fetchStats()]);

      // Update selected client if viewing details
      if (selectedClient) {
        await fetchClientDetails(selectedClient.id);
      }
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  // Handle row click to view details
  const handleRowClick = (client: Client) => {
    fetchClientDetails(client.id);
  };

  // Calculate pagination
  const totalPages = Math.ceil(totalClients / ITEMS_PER_PAGE);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-primary-800">Players</h1>
          <p className="mt-1 text-primary-600">
            Manage your club's players
          </p>
        </div>
        <Button onClick={() => setShowCreateForm(true)}>
          <svg
            className="w-5 h-5 mr-2"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
            />
          </svg>
          New Player
        </Button>
      </div>

      {/* Error Message */}
      {error && (
        <div className="rounded-md bg-red-50 border border-red-200 p-4">
          <div className="flex items-center">
            <svg
              className="h-5 w-5 text-red-400"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                clipRule="evenodd"
              />
            </svg>
            <p className="ml-3 text-sm text-red-700">{error}</p>
            <button
              onClick={() => setError(null)}
              className="ml-auto text-red-500 hover:text-red-700"
            >
              <svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                <path
                  fillRule="evenodd"
                  d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                  clipRule="evenodd"
                />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {loadingStats ? (
          <>
            <StatCardSkeleton />
            <StatCardSkeleton />
            <StatCardSkeleton />
          </>
        ) : (
          <>
            <StatCard
              title="Total Players"
              value={stats.totalClients}
              color="primary"
              icon={
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
                  />
                </svg>
              }
            />
            <StatCard
              title="With Membership"
              value={stats.withMembership}
              color="accent"
              icon={
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"
                  />
                </svg>
              }
            />
            <StatCard
              title="New This Month"
              value={stats.newThisMonth}
              color="green"
              icon={
                <svg
                  className="w-6 h-6"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
                  />
                </svg>
              }
            />
          </>
        )}
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-4">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* Search */}
            <div className="flex-1">
              <Input
                type="text"
                placeholder="Search by name, email or phone..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>

            {/* Membership Filter */}
            <div className="flex gap-2 overflow-x-auto pb-2 sm:pb-0">
              {membershipFilters.map((filter) => (
                <Button
                  key={filter.value}
                  variant={membershipFilter === filter.value ? "default" : "outline"}
                  size="sm"
                  onClick={() => setMembershipFilter(filter.value)}
                  className="whitespace-nowrap"
                >
                  {filter.label}
                </Button>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Clients Table */}
      <Card>
        <ClientTable
          clients={clients}
          onRowClick={handleRowClick}
          onEdit={(client) => setEditingClient(client)}
          onDelete={handleDeleteClient}
          isLoading={loadingClients}
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      </Card>

      {/* Create Client Form Modal */}
      {showCreateForm && (
        <ClientForm
          onSubmit={handleCreateClient}
          onCancel={() => setShowCreateForm(false)}
          isLoading={formLoading}
          mode="create"
        />
      )}

      {/* Edit Client Form Modal */}
      {editingClient && (
        <ClientForm
          initialData={{
            firstName: editingClient.firstName,
            lastName: editingClient.lastName,
            email: editingClient.email || "",
            phone: editingClient.phone || "",
            avatar: editingClient.avatar || "",
          }}
          onSubmit={handleUpdateClient}
          onCancel={() => setEditingClient(null)}
          isLoading={formLoading}
          mode="edit"
        />
      )}

      {/* Client Detail Dialog */}
      {selectedClient && !editingClient && (
        <ClientDetailDialog
          client={selectedClient}
          onClose={() => setSelectedClient(null)}
          onEdit={() => {
            setEditingClient(selectedClient);
          }}
          onAssignMembership={() => {
            setShowAssignMembership(true);
          }}
        />
      )}

      {/* Assign Membership Dialog */}
      {showAssignMembership && selectedClient && (
        <AssignMembershipDialog
          plans={membershipPlans}
          preselectedClient={{
            id: selectedClient.id,
            firstName: selectedClient.firstName,
            lastName: selectedClient.lastName,
            email: selectedClient.email,
            phone: selectedClient.phone,
          }}
          onClose={() => setShowAssignMembership(false)}
          onAssign={handleAssignMembership}
          isLoading={formLoading}
        />
      )}
    </div>
  );
}
