import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { CreditCard, RefreshCw, CheckCircle, XCircle, Loader2, Zap } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { loadStripe } from "@stripe/stripe-js";
import { Elements, PaymentElement, useStripe, useElements } from "@stripe/react-stripe-js";

interface Enrollment {
  id: string;
  association_id: string;
  owner_id: string | null;
  unit_id: string | null;
  payment_method_type: string;
  is_active: boolean;
  created_at: string;
}

interface OwnerUnit {
  owner_id: string;
  unit_id: string;
  association_id: string;
  association_name: string;
  unit_label: string;
  owner_name: string;
}

function SetupForm({
  clientSecret,
  onSuccess,
  onCancel,
}: {
  clientSecret: string;
  onSuccess: (setupIntentId: string) => void;
  onCancel: () => void;
}) {
  const stripe = useStripe();
  const elements = useElements();
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!stripe || !elements) return;

    setLoading(true);
    const { error, setupIntent } = await stripe.confirmSetup({
      elements,
      redirect: "if_required",
    });

    if (error) {
      toast.error(error.message || "Failed to save payment method");
      setLoading(false);
    } else if (setupIntent?.status === "succeeded") {
      onSuccess(setupIntent.id);
    } else {
      toast.error("Setup not completed. Please try again.");
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <PaymentElement />
      <div className="flex gap-2 pt-2">
        <Button type="submit" disabled={!stripe || loading} className="flex-1">
          {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Zap className="h-4 w-4 mr-2" />}
          Save Payment Method
        </Button>
        <Button type="button" variant="outline" onClick={onCancel} disabled={loading}>
          Cancel
        </Button>
      </div>
    </form>
  );
}

export default function ClientPaymentPlansPage() {
  const [tab, setTab] = useState("autopay");
  const [enrollments, setEnrollments] = useState<Enrollment[]>([]);
  const [ownerUnits, setOwnerUnits] = useState<OwnerUnit[]>([]);
  const [loading, setLoading] = useState(true);
  const [enrolling, setEnrolling] = useState(false);

  // Setup flow state
  const [selectedAssociation, setSelectedAssociation] = useState("");
  const [selectedOwner, setSelectedOwner] = useState("");
  const [selectedUnit, setSelectedUnit] = useState("");
  const [paymentMethodType, setPaymentMethodType] = useState("card");
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [stripePromise, setStripePromise] = useState<any>(null);
  const [setupCustomerId, setSetupCustomerId] = useState("");

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

  const loadData = async () => {
    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      // Get user's owner records with associations/units
      const { data: owners } = await supabase
        .from("owners")
        .select("id, first_name, last_name, association_id, associations(name), unit_id, units(unit_number)")
        .eq("user_id", user.id)
        .neq("status", "archived");

      if (owners) {
        setOwnerUnits(
          owners.map((o: any) => ({
            owner_id: o.id,
            unit_id: o.unit_id,
            association_id: o.association_id,
            association_name: o.associations?.name || "Unknown",
            unit_label: o.units?.unit_number || "N/A",
            owner_name: `${o.first_name || ""} ${o.last_name || ""}`.trim(),
          }))
        );
      }

      // Get enrollments
      const { data: enrollData } = await supabase
        .from("autopay_enrollments")
        .select("*")
        .eq("enrolled_by", user.id)
        .order("created_at", { ascending: false });

      setEnrollments((enrollData as Enrollment[]) || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const startEnrollment = async () => {
    if (!selectedAssociation) {
      toast.error("Please select a property");
      return;
    }

    setEnrolling(true);
    try {
      const session = (await supabase.auth.getSession()).data.session;
      const projectId = import.meta.env.VITE_SUPABASE_PROJECT_ID;

      const res = await fetch(
        `https://${projectId}.supabase.co/functions/v1/setup-autopay`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session?.access_token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            association_id: selectedAssociation,
            owner_id: selectedOwner || null,
            unit_id: selectedUnit || null,
            payment_method_type: paymentMethodType,
          }),
        }
      );

      const data = await res.json();
      if (data.error) {
        toast.error(data.error);
        setEnrolling(false);
        return;
      }

      setClientSecret(data.clientSecret);
      setSetupCustomerId(data.customerId);
      setStripePromise(loadStripe(data.publishableKey));
    } catch (err: any) {
      toast.error(err.message || "Failed to start enrollment");
    } finally {
      setEnrolling(false);
    }
  };

  const handleSetupSuccess = async (setupIntentId: string) => {
    try {
      const session = (await supabase.auth.getSession()).data.session;
      const projectId = import.meta.env.VITE_SUPABASE_PROJECT_ID;

      const res = await fetch(
        `https://${projectId}.supabase.co/functions/v1/confirm-autopay`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session?.access_token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            setup_intent_id: setupIntentId,
            association_id: selectedAssociation,
            owner_id: selectedOwner || null,
            unit_id: selectedUnit || null,
            customer_id: setupCustomerId,
            payment_method_type: paymentMethodType,
          }),
        }
      );

      const data = await res.json();
      if (data.error) {
        toast.error(data.error);
      } else {
        toast.success("Autopay enrolled successfully!");
        setClientSecret(null);
        setStripePromise(null);
        loadData();
      }
    } catch (err: any) {
      toast.error("Failed to confirm enrollment");
    }
  };

  const cancelEnrollment = async (id: string) => {
    const { error } = await supabase
      .from("autopay_enrollments")
      .update({ is_active: false })
      .eq("id", id);

    if (error) {
      toast.error("Failed to cancel autopay");
    } else {
      toast.success("Autopay cancelled");
      loadData();
    }
  };

  const activeEnrollments = enrollments.filter((e) => e.is_active);

  // Auto-select when user has only one property
  useEffect(() => {
    if (ownerUnits.length === 1 && !selectedAssociation) {
      setSelectedAssociation(ownerUnits[0].association_id);
      setSelectedOwner(ownerUnits[0].owner_id);
      setSelectedUnit(ownerUnits[0].unit_id);
    }
  }, [ownerUnits]);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Payment Plans & Autopay</h1>
        <p className="text-muted-foreground mt-1">Manage payment plans and automatic payments.</p>
      </div>

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="autopay">
            <Zap className="h-4 w-4 mr-1" /> Autopay
          </TabsTrigger>
          <TabsTrigger value="plans">Payment Plans</TabsTrigger>
        </TabsList>

        <TabsContent value="autopay" className="space-y-4 mt-4">
          {/* Active Enrollments */}
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : (
            <>
              {activeEnrollments.length > 0 && (
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-lg flex items-center gap-2">
                      <CheckCircle className="h-5 w-5 text-green-500" /> Active Autopay
                    </CardTitle>
                    <CardDescription>Your saved payment methods for automatic charges</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="divide-y">
                      {activeEnrollments.map((e) => {
                        const ou = ownerUnits.find(
                          (o) => o.association_id === e.association_id
                        );
                        return (
                          <div key={e.id} className="flex items-center justify-between py-3">
                            <div>
                              <p className="text-sm font-medium">
                                {ou?.association_name || "Association"}
                                {ou?.unit_label ? ` — Unit ${ou.unit_label}` : ""}
                              </p>
                              <div className="flex items-center gap-2 mt-1">
                                <Badge variant="outline" className="text-xs">
                                  <CreditCard className="h-3 w-3 mr-1" />
                                  {e.payment_method_type === "us_bank_account" ? "Bank Account" : "Card"}
                                </Badge>
                                <span className="text-xs text-muted-foreground">
                                  Since {new Date(e.created_at).toLocaleDateString()}
                                </span>
                              </div>
                            </div>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-destructive hover:text-destructive"
                              onClick={() => cancelEnrollment(e.id)}
                            >
                              <XCircle className="h-4 w-4 mr-1" /> Cancel
                            </Button>
                          </div>
                        );
                      })}
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* Enroll Form */}
              {clientSecret && stripePromise ? (
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">Save Payment Method</CardTitle>
                    <CardDescription>Enter your card or bank details for automatic payments</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Elements stripe={stripePromise} options={{ clientSecret }}>
                      <SetupForm
                        clientSecret={clientSecret}
                        onSuccess={handleSetupSuccess}
                        onCancel={() => {
                          setClientSecret(null);
                          setStripePromise(null);
                        }}
                      />
                    </Elements>
                  </CardContent>
                </Card>
              ) : (
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Zap className="h-5 w-5 text-primary" /> Enroll in Autopay
                    </CardTitle>
                    <CardDescription>
                      Save a payment method to be automatically charged when assessments are due
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {ownerUnits.length > 1 && (
                      <div className="space-y-2">
                        <Label>Property</Label>
                        <Select value={selectedAssociation} onValueChange={(v) => {
                          setSelectedAssociation(v);
                          const ou = ownerUnits.find((o) => o.association_id === v);
                          if (ou) {
                            setSelectedOwner(ou.owner_id);
                            setSelectedUnit(ou.unit_id);
                          }
                        }}>
                          <SelectTrigger>
                            <SelectValue placeholder="Select property" />
                          </SelectTrigger>
                          <SelectContent>
                            {ownerUnits.map((ou) => (
                              <SelectItem key={ou.owner_id} value={ou.association_id}>
                                {ou.association_name} — Unit {ou.unit_label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    )}

                    <div className="space-y-2">
                      <Label>Payment Method</Label>
                      <Select value={paymentMethodType} onValueChange={setPaymentMethodType}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="card">Credit / Debit Card</SelectItem>
                          <SelectItem value="us_bank_account">Bank Account (ACH)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <Button onClick={startEnrollment} disabled={enrolling || !selectedAssociation}>
                      {enrolling ? (
                        <Loader2 className="h-4 w-4 animate-spin mr-2" />
                      ) : (
                        <CreditCard className="h-4 w-4 mr-2" />
                      )}
                      Set Up Autopay
                    </Button>
                  </CardContent>
                </Card>
              )}
            </>
          )}
        </TabsContent>

        <TabsContent value="plans" className="mt-4">
          <div className="text-center py-12 text-muted-foreground bg-muted/50 rounded-xl border border-dashed">
            <p>No payment plans found.</p>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
