import { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  UserCircle, Save, Home, Globe, Users, CreditCard, Building2,
  Phone, Mail, Info, Plus, AlertCircle, KeyRound, Bell, Palette,
} from "lucide-react";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { useAuth } from "@/contexts/AuthContext";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import NotificationPreferencesCard from "@/components/profile/NotificationPreferencesCard";
import PersonalDetailsCard from "@/components/profile/PersonalDetailsCard";
import AppearanceCard from "@/components/profile/AppearanceCard";
import UsernameCard from "@/components/profile/UsernameCard";

export default function HomeownerProfilePage() {
  const { currentOwner, association, unit, loading: ctxLoading } = useHomeowner();
  const { profile, user } = useAuth();

  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [mailingAddress, setMailingAddress] = useState("");
  const [saving, setSaving] = useState(false);

  // Initialize form values from owner data
  useEffect(() => {
    if (currentOwner) {
      setFullName(`${currentOwner.first_name} ${currentOwner.last_name}`);
      setPhone(currentOwner.phone || "");
      setEmail(currentOwner.email || "");
      setMailingAddress(currentOwner.mailing_address || "");
    }
  }, [currentOwner]);

  const handleSave = async () => {
    if (!currentOwner) return;
    setSaving(true);

    const nameParts = fullName.trim().split(" ");
    const firstName = nameParts[0] || currentOwner.first_name;
    const lastName = nameParts.slice(1).join(" ") || currentOwner.last_name;

    const { error } = await supabase
      .from("owners")
      .update({
        first_name: firstName,
        last_name: lastName,
        phone: phone || null,
        email: email || null,
        mailing_address: mailingAddress || null,
      })
      .eq("id", currentOwner.id);

    setSaving(false);

    if (error) {
      toast.error("Failed to save changes");
    } else {
      toast.success("Profile updated successfully");
    }
  };

  if (ctxLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!currentOwner) {
    return (
      <div className="text-center py-20 space-y-2">
        <AlertCircle className="h-10 w-10 text-muted-foreground/30 mx-auto" />
        <p className="text-lg font-medium text-foreground">No property linked to your account</p>
        <p className="text-sm text-muted-foreground">Please contact your property management company.</p>
      </div>
    );
  }

  const balance = currentOwner.balance ?? 0;
  const propertyAddress = unit?.address || currentOwner.property_address || currentOwner.street_address || "—";

  return (
    <div className="space-y-6">
      {/* Profile Header */}
      <Card>
        <CardContent className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center">
              <UserCircle className="h-8 w-8 text-muted-foreground" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-foreground">{currentOwner.first_name} {currentOwner.last_name}</h1>
              <p className="text-sm text-muted-foreground flex items-center gap-1.5">
                <Home className="h-3.5 w-3.5" /> {propertyAddress}
              </p>
            </div>
          </div>
          <span className="text-sm font-medium text-muted-foreground">
            Status: <span className="text-foreground">{balance > 0 ? "Balance Due" : "Current"}</span>
          </span>
        </CardContent>
      </Card>

      {/* Tabs */}
      <Tabs defaultValue="personal">
        <TabsList className="flex-wrap">
          <TabsTrigger value="personal" className="gap-1.5">
            <Globe className="h-3.5 w-3.5" /> Personal Info
          </TabsTrigger>
          <TabsTrigger value="property" className="gap-1.5">
            <Building2 className="h-3.5 w-3.5" /> Property Details
          </TabsTrigger>
          <TabsTrigger value="details" className="gap-1.5">
            <Info className="h-3.5 w-3.5" /> About Me
          </TabsTrigger>
          <TabsTrigger value="notifications" className="gap-1.5">
            <Bell className="h-3.5 w-3.5" /> Notifications
          </TabsTrigger>
          <TabsTrigger value="security" className="gap-1.5">
            <KeyRound className="h-3.5 w-3.5" /> Security
          </TabsTrigger>
          <TabsTrigger value="appearance" className="gap-1.5">
            <Palette className="h-3.5 w-3.5" /> Appearance
          </TabsTrigger>
          <TabsTrigger value="tenants" className="gap-1.5">
            <Users className="h-3.5 w-3.5" /> Tenants
          </TabsTrigger>
          <TabsTrigger value="payment-history" className="gap-1.5">
            <CreditCard className="h-3.5 w-3.5" /> Payment History
          </TabsTrigger>
        </TabsList>

        <TabsContent value="details">
          {user && (
            <PersonalDetailsCard
              userId={user.id}
              initial={{
                bio: (profile as any)?.bio,
                mailing_street: (profile as any)?.mailing_street,
                mailing_city: (profile as any)?.mailing_city,
                mailing_state: (profile as any)?.mailing_state,
                mailing_zip: (profile as any)?.mailing_zip,
                emergency_contact_name: (profile as any)?.emergency_contact_name,
                emergency_contact_phone: (profile as any)?.emergency_contact_phone,
                preferred_language: (profile as any)?.preferred_language,
              }}
            />
          )}
        </TabsContent>

        <TabsContent value="notifications">
          {user && (
            <NotificationPreferencesCard
              userId={user.id}
              initialPreferences={(profile as any)?.notification_preferences}
              initialPreferredEmail={(profile as any)?.preferred_notification_email}
            />
          )}
        </TabsContent>

        {/* Personal Info */}
        <TabsContent value="personal">
          <Card>
            <CardContent className="space-y-5">
              <div>
                <h2 className="text-lg font-semibold text-foreground">Personal Information</h2>
                <p className="text-sm text-muted-foreground">Update your contact and mailing details.</p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Full Name</Label>
                  <Input value={fullName} onChange={(e) => setFullName(e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>Phone Number</Label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input value={phone} onChange={(e) => setPhone(e.target.value)} className="pl-9" />
                  </div>
                </div>
              </div>
              <div className="space-y-2">
                <Label>Email Address</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input value={email} onChange={(e) => setEmail(e.target.value)} className="pl-9" />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Mailing Address (if different from property)</Label>
                <Input value={mailingAddress} onChange={(e) => setMailingAddress(e.target.value)} />
              </div>
              <div className="flex justify-end">
                <Button className="gap-2" onClick={handleSave} disabled={saving}>
                  <Save className="h-4 w-4" /> {saving ? "Saving..." : "Save Changes"}
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Property Details */}
        <TabsContent value="property">
          <Card>
            <CardContent className="space-y-5">
              <div>
                <h2 className="text-lg font-semibold text-foreground">Unit Details</h2>
                <p className="text-sm text-muted-foreground">View information about your assigned property.</p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-y-4 gap-x-8">
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Unit ID / Number</p>
                  <p className="text-sm font-semibold text-foreground mt-0.5">{unit?.unit_number || "—"}</p>
                </div>
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Property Address</p>
                  <p className="text-sm font-semibold text-foreground mt-0.5">{propertyAddress}</p>
                </div>
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Association / Community</p>
                  <p className="text-sm font-semibold text-foreground mt-0.5">{association?.name || "—"}</p>
                </div>
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Account Number</p>
                  <p className="text-sm font-semibold text-foreground mt-0.5">{unit?.account_number || "—"}</p>
                </div>
              </div>
              <div className="flex items-start gap-3 rounded-md bg-primary/5 border border-primary/10 p-4 mt-2">
                <Info className="h-5 w-5 text-primary mt-0.5 shrink-0" />
                <div>
                  <p className="text-sm font-medium text-foreground">Need changes to this section?</p>
                  <p className="text-sm text-muted-foreground">
                    Property details are managed by the association. If this information is incorrect, please contact management.
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Security / Change Password */}
        <TabsContent value="security">
          <div className="space-y-4">
            <UsernameCard userId={user.id} />
            <ChangePasswordSection />
          </div>
        </TabsContent>

        <TabsContent value="appearance">
          <AppearanceCard />
        </TabsContent>

        {/* Tenants */}
        <TabsContent value="tenants">
          <Card>
            <CardContent className="space-y-5">
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-lg font-semibold text-foreground">Tenant Information</h2>
                  <p className="text-sm text-muted-foreground">Manage occupants for this unit.</p>
                </div>
                <Button variant="outline" className="gap-2">
                  <Plus className="h-4 w-4" /> Add Tenant
                </Button>
              </div>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Lease Period</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
                      No tenants recorded for this unit.
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Payment History */}
        <TabsContent value="payment-history">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card>
              <CardContent className="text-center space-y-3">
                <p className="text-sm font-medium text-primary uppercase">Outstanding Balance</p>
                <p className="text-3xl font-bold text-primary">${Math.abs(balance).toFixed(2)}</p>
                <Button className="w-full">Make a Payment</Button>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-base font-semibold text-foreground">Recent Transactions</h3>
                  <Button variant="outline" size="sm">View Full Ledger</Button>
                </div>
                <p className="text-xs text-muted-foreground mb-3">Your last 5 ledger entries.</p>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead>Description</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    <TableRow>
                      <TableCell colSpan={3} className="text-center py-6 text-muted-foreground text-sm">
                        No recent transactions found.
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function ChangePasswordSection() {
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [saving, setSaving] = useState(false);

  const handleChangePassword = async () => {
    if (newPassword.length < 6) {
      toast.error("Password must be at least 6 characters");
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }
    setSaving(true);
    const { error } = await supabase.auth.updateUser({ password: newPassword });
    setSaving(false);
    if (error) {
      toast.error(error.message || "Failed to update password");
    } else {
      toast.success("Password updated successfully");
      setNewPassword("");
      setConfirmPassword("");
    }
  };

  return (
    <Card>
      <CardContent className="space-y-5">
        <div>
          <h2 className="text-lg font-semibold text-foreground">Change Password</h2>
          <p className="text-sm text-muted-foreground">Update your account password.</p>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>New Password</Label>
            <div className="relative">
              <KeyRound className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="pl-9" placeholder="••••••••" />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Confirm Password</Label>
            <div className="relative">
              <KeyRound className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className="pl-9" placeholder="••••••••" />
            </div>
          </div>
        </div>
        <div className="flex justify-end">
          <Button onClick={handleChangePassword} disabled={saving || !newPassword} className="gap-2">
            <KeyRound className="h-4 w-4" /> {saving ? "Updating…" : "Update Password"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
