"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PlanCard } from "@/components/memberships/plan-card";
import { PlanForm } from "@/components/memberships/plan-form";
import { MembershipTable } from "@/components/memberships/membership-table";
import { AssignMembershipDialog } from "@/components/memberships/assign-membership-dialog";
import { cn } from "@/lib/utils";

interface MembershipPlan {
  id: string;
  name: string;
  description: string | null;
  price: number | string;
  durationMonths: number;
  courtHours: number | null;
  discountPercent: number | string | null;
  benefits: string[] | null;
  isActive: boolean;
  subscriberCount: number;
  benefitsSummary?: {
    freeHours: number;
    bookingDiscount: number;
    extraBenefits: string[];
  };
}

interface Membership {
  id: string;
  startDate: string;
  endDate: string;
  status: "ACTIVE" | "EXPIRED" | "CANCELLED" | "SUSPENDED";
  remainingHours: number | null;
  autoRenew: boolean;
  isExpiring?: boolean;
  daysUntilExpiry?: number | null;
  plan: {
    id: string;
    name: string;
    price: number | string;
    durationMonths: number;
    courtHours: number | null;
  };
  client: {
    id: string;
    firstName: string;
    lastName: string;
    email: string | null;
    phone: string | null;
  };
  benefitsSummary?: {
    freeHours: number;
    hoursRemaining: number;
  };
}

interface MembershipsResponse {
  data: Membership[];
  pagination: {
    total: number;
    limit: number;
    offset: number;
    hasMore: boolean;
  };
}

const statusFilters = [
  { value: "", label: "All" },
  { value: "ACTIVE", label: "Active" },
  { value: "EXPIRED", label: "Expired" },
  { value: "CANCELLED", label: "Cancelled" },
];

export default function MembershipsPage() {
  // Plans state
  const [plans, setPlans] = useState<MembershipPlan[]>([]);
  const [loadingPlans, setLoadingPlans] = useState(true);
  const [showPlanForm, setShowPlanForm] = useState(false);
  const [editingPlan, setEditingPlan] = useState<MembershipPlan | null>(null);
  const [planFormLoading, setPlanFormLoading] = useState(false);

  // Memberships state
  const [memberships, setMemberships] = useState<Membership[]>([]);
  const [loadingMemberships, setLoadingMemberships] = useState(true);
  const [statusFilter, setStatusFilter] = useState("");
  const [planFilter, setPlanFilter] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [assignLoading, setAssignLoading] = useState(false);

  // Stats
  const [stats, setStats] = useState({
    totalActive: 0,
    expiringSoon: 0,
  });

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

  // Fetch plans
  const fetchPlans = useCallback(async () => {
    setLoadingPlans(true);
    try {
      const response = await fetch("/api/membership-plans?includeInactive=true");
      if (!response.ok) throw new Error("Error loading plans");
      const data = await response.json();
      setPlans(data);
    } catch (err) {
      console.error("Error fetching plans:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoadingPlans(false);
    }
  }, []);

  // Fetch memberships
  const fetchMemberships = useCallback(async () => {
    setLoadingMemberships(true);
    try {
      const params = new URLSearchParams();
      if (statusFilter) params.append("status", statusFilter);
      if (planFilter) params.append("planId", planFilter);
      if (searchQuery) params.append("search", searchQuery);

      const response = await fetch(`/api/memberships?${params.toString()}`);
      if (!response.ok) throw new Error("Error loading memberships");
      const data: MembershipsResponse = await response.json();
      setMemberships(data.data);

      // Calculate stats
      const active = data.data.filter(m => m.status === "ACTIVE");
      const expiring = data.data.filter(m => m.isExpiring);
      setStats({
        totalActive: active.length,
        expiringSoon: expiring.length,
      });
    } catch (err) {
      console.error("Error fetching memberships:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoadingMemberships(false);
    }
  }, [statusFilter, planFilter, searchQuery]);

  useEffect(() => {
    fetchPlans();
  }, [fetchPlans]);

  useEffect(() => {
    fetchMemberships();
  }, [fetchMemberships]);

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

  useEffect(() => {
    if (debouncedSearch !== undefined) {
      fetchMemberships();
    }
  }, [debouncedSearch]);

  // Handle plan creation/update
  const handlePlanSubmit = async (data: {
    name: string;
    description: string;
    price: number;
    durationMonths: number;
    freeHours: number;
    bookingDiscount: number;
    storeDiscount: number;
    extraBenefits: string;
  }) => {
    setPlanFormLoading(true);
    try {
      const extraBenefitsArray = data.extraBenefits
        .split("\n")
        .map(b => b.trim())
        .filter(b => b.length > 0);

      const payload = {
        name: data.name,
        description: data.description || undefined,
        price: data.price,
        durationMonths: data.durationMonths,
        freeHours: data.freeHours || undefined,
        bookingDiscount: data.bookingDiscount || undefined,
        storeDiscount: data.storeDiscount || undefined,
        extraBenefits: extraBenefitsArray.length > 0 ? extraBenefitsArray : undefined,
      };

      const url = editingPlan
        ? `/api/membership-plans/${editingPlan.id}`
        : "/api/membership-plans";
      const method = editingPlan ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

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

      setShowPlanForm(false);
      setEditingPlan(null);
      await fetchPlans();
    } catch (err) {
      throw err;
    } finally {
      setPlanFormLoading(false);
    }
  };

  // Handle plan deletion
  const handleDeletePlan = async (plan: MembershipPlan) => {
    if (!confirm(`Are you sure you want to delete the plan "${plan.name}"? This action will deactivate it.`)) {
      return;
    }

    try {
      const response = await fetch(`/api/membership-plans/${plan.id}`, {
        method: "DELETE",
      });

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

      await fetchPlans();
    } catch (err) {
      console.error("Error deleting plan:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  // Handle membership assignment
  const handleAssignMembership = async (data: {
    clientId: string;
    planId: string;
    startDate: string;
    endDate: string;
  }) => {
    setAssignLoading(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");
      }

      setShowAssignDialog(false);
      await Promise.all([fetchMemberships(), fetchPlans()]);
    } catch (err) {
      throw err;
    } finally {
      setAssignLoading(false);
    }
  };

  // Handle membership renewal
  const handleRenewMembership = async (membership: Membership) => {
    // For renewal, we create a new membership with the same plan
    const startDate = new Date();
    const endDate = new Date();
    endDate.setMonth(endDate.getMonth() + membership.plan.durationMonths);

    try {
      const response = await fetch("/api/memberships", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientId: membership.client.id,
          planId: membership.plan.id,
          startDate: startDate.toISOString(),
          endDate: endDate.toISOString(),
        }),
      });

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

      await Promise.all([fetchMemberships(), fetchPlans()]);
    } catch (err) {
      console.error("Error renewing membership:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  // Handle membership cancellation
  const handleCancelMembership = async (membership: Membership) => {
    if (!confirm(`Are you sure you want to cancel the membership for ${membership.client.firstName} ${membership.client.lastName}?`)) {
      return;
    }

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

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

      await Promise.all([fetchMemberships(), fetchPlans()]);
    } catch (err) {
      console.error("Error cancelling membership:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  // Filter active plans for assignment dialog
  const activePlans = plans.filter(p => p.isActive);

  return (
    <div className="space-y-8">
      {/* 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">Memberships</h1>
          <p className="mt-1 text-primary-600">
            Manage plans and memberships for your players
          </p>
        </div>
      </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-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-full bg-accent-100">
                <svg className="w-6 h-6 text-accent-600" 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 0z" />
                </svg>
              </div>
              <div>
                <p className="text-sm text-primary-500">Active Memberships</p>
                <p className="text-2xl font-bold text-primary-800">{stats.totalActive}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className={cn(stats.expiringSoon > 0 && "border-yellow-300 bg-yellow-50")}>
          <CardContent className="pt-6">
            <div className="flex items-center gap-4">
              <div className={cn(
                "p-3 rounded-full",
                stats.expiringSoon > 0 ? "bg-yellow-100" : "bg-primary-100"
              )}>
                <svg className={cn(
                  "w-6 h-6",
                  stats.expiringSoon > 0 ? "text-yellow-600" : "text-primary-600"
                )} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div>
                <p className="text-sm text-primary-500">Expiring Soon</p>
                <p className="text-2xl font-bold text-primary-800">{stats.expiringSoon}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-full bg-purple-100">
                <svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                </svg>
              </div>
              <div>
                <p className="text-sm text-primary-500">Active Plans</p>
                <p className="text-2xl font-bold text-primary-800">{activePlans.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-full bg-green-100">
                <svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div>
                <p className="text-sm text-primary-500">Total Subscribers</p>
                <p className="text-2xl font-bold text-primary-800">
                  {plans.reduce((sum, p) => sum + p.subscriberCount, 0)}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Plans Section */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-primary-800">Membership Plans</h2>
          <Button onClick={() => setShowPlanForm(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="M12 4v16m8-8H4" />
            </svg>
            New Plan
          </Button>
        </div>

        {loadingPlans ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
              <p className="text-primary-500">Loading plans...</p>
            </div>
          </div>
        ) : plans.length === 0 ? (
          <Card className="py-12">
            <CardContent className="text-center">
              <svg
                className="w-12 h-12 mx-auto mb-3 text-primary-300"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
              <p className="font-medium text-primary-600">No plans</p>
              <p className="text-sm text-primary-500 mt-1">Create your first membership plan</p>
              <Button className="mt-4" onClick={() => setShowPlanForm(true)}>
                Create Plan
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {plans.map((plan) => (
              <PlanCard
                key={plan.id}
                plan={plan}
                isAdmin={true}
                onEdit={(p) => {
                  setEditingPlan(p);
                  setShowPlanForm(true);
                }}
                onDelete={handleDeletePlan}
              />
            ))}
          </div>
        )}
      </section>

      {/* Memberships Section */}
      <section>
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
          <h2 className="text-xl font-semibold text-primary-800">Memberships</h2>
          <Button variant="accent" onClick={() => setShowAssignDialog(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>
            Assign Membership
          </Button>
        </div>

        {/* Filters */}
        <Card className="mb-4">
          <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 player name..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full"
                />
              </div>

              {/* Plan Filter */}
              <div className="sm:w-48">
                <select
                  value={planFilter}
                  onChange={(e) => setPlanFilter(e.target.value)}
                  className="flex h-10 w-full rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2"
                >
                  <option value="">All plans</option>
                  {activePlans.map((plan) => (
                    <option key={plan.id} value={plan.id}>
                      {plan.name}
                    </option>
                  ))}
                </select>
              </div>

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

        {/* Memberships Table */}
        <Card>
          <MembershipTable
            memberships={memberships}
            onRenew={handleRenewMembership}
            onCancel={handleCancelMembership}
            isLoading={loadingMemberships}
          />
        </Card>
      </section>

      {/* Plan Form Modal */}
      {showPlanForm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto">
          <div className="my-8">
            <PlanForm
              initialData={editingPlan || undefined}
              onSubmit={handlePlanSubmit}
              onCancel={() => {
                setShowPlanForm(false);
                setEditingPlan(null);
              }}
              isLoading={planFormLoading}
              mode={editingPlan ? "edit" : "create"}
            />
          </div>
        </div>
      )}

      {/* Assign Membership Dialog */}
      {showAssignDialog && (
        <AssignMembershipDialog
          plans={activePlans}
          onClose={() => setShowAssignDialog(false)}
          onAssign={handleAssignMembership}
          isLoading={assignLoading}
        />
      )}
    </div>
  );
}
