import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Edit2, Save, X, Plus, Trash2, Car, Dog, Info, Users2 } from "lucide-react";

interface ParkingData { id?: string; spaces: string; spots: string; type: string; notes: string }
interface PetData { id?: string; name: string; type: string; breed: string; weight: string; notes: string; isNew?: boolean }
interface GeneralData { id?: string; utilities: string; amenities: string; restrictions: string }
interface OccupantData { id?: string; name: string; relationship: string; phone: string; email: string; isNew?: boolean }

export default function OtherTab({ unitId }: { unitId: string }) {
  const { toast } = useToast();
  const [isEditing, setIsEditing] = useState(false);
  const [loading, setLoading] = useState(true);

  const [parking, setParking] = useState<ParkingData>({ spaces: "", spots: "", type: "", notes: "" });
  const [pets, setPets] = useState<PetData[]>([]);
  const [generalInfo, setGeneralInfo] = useState<GeneralData>({ utilities: "", amenities: "", restrictions: "" });
  const [occupants, setOccupants] = useState<OccupantData[]>([]);

  const [editParking, setEditParking] = useState<ParkingData>({ spaces: "", spots: "", type: "", notes: "" });
  const [editPets, setEditPets] = useState<PetData[]>([]);
  const [editGeneral, setEditGeneral] = useState<GeneralData>({ utilities: "", amenities: "", restrictions: "" });
  const [editOccupants, setEditOccupants] = useState<OccupantData[]>([]);

  useEffect(() => { if (unitId) fetchAllData(); }, [unitId]);

  const fetchAllData = async () => {
    try {
      const [pk, pt, gi, oc] = await Promise.all([
        supabase.from("unit_parking").select("*").eq("unit_id", unitId).maybeSingle(),
        supabase.from("unit_pets").select("*").eq("unit_id", unitId),
        supabase.from("unit_general_info").select("*").eq("unit_id", unitId).maybeSingle(),
        supabase.from("unit_occupants").select("*").eq("unit_id", unitId),
      ]);
      if (pk.data) setParking(pk.data as any); else setParking({ spaces: "", spots: "", type: "", notes: "" });
      if (pt.data) setPets(pt.data as any);
      if (gi.data) setGeneralInfo(gi.data as any); else setGeneralInfo({ utilities: "", amenities: "", restrictions: "" });
      if (oc.data) setOccupants(oc.data as any);
    } catch (e) { console.warn("Error fetching unit data:", e); }
    finally { setLoading(false); }
  };

  const handleEditClick = () => {
    setEditParking({ ...parking });
    setEditPets([...pets]);
    setEditGeneral({ ...generalInfo });
    setEditOccupants([...occupants]);
    setIsEditing(true);
  };

  const handleSave = async () => {
    if (editOccupants.some(o => !o.name || !o.relationship)) {
      toast({ title: "Validation Error", description: "Occupant name and relationship required.", variant: "destructive" });
      return;
    }
    try {
      const pkPayload = { unit_id: unitId, spaces: editParking.spaces, spots: editParking.spots, type: editParking.type, notes: editParking.notes };
      if (parking.id) await supabase.from("unit_parking").update(pkPayload).eq("id", parking.id);
      else await supabase.from("unit_parking").insert([pkPayload]);

      const giPayload = { unit_id: unitId, utilities: editGeneral.utilities, amenities: editGeneral.amenities, restrictions: editGeneral.restrictions };
      if (generalInfo.id) await supabase.from("unit_general_info").update(giPayload).eq("id", generalInfo.id);
      else await supabase.from("unit_general_info").insert([giPayload]);

      for (const p of editPets) {
        const payload = { unit_id: unitId, type: p.type, name: p.name, breed: p.breed, weight: p.weight, notes: p.notes };
        if (p.isNew) await supabase.from("unit_pets").insert([payload]);
        else await supabase.from("unit_pets").update(payload).eq("id", p.id!);
      }

      for (const o of editOccupants) {
        const payload = { unit_id: unitId, name: o.name, relationship: o.relationship, phone: o.phone, email: o.email };
        if (o.isNew) await supabase.from("unit_occupants").insert([payload]);
        else await supabase.from("unit_occupants").update(payload).eq("id", o.id!);
      }

      await fetchAllData();
      setIsEditing(false);
      toast({ title: "Success", description: "Information updated." });
    } catch (error) {
      console.error(error);
      toast({ title: "Error", description: "Failed to update.", variant: "destructive" });
    }
  };

  if (loading) return <div className="p-8 text-center text-muted-foreground animate-pulse">Loading...</div>;

  return (
    <div className="space-y-6">
      <div className="flex justify-end">
        {!isEditing ? (
          <Button variant="outline" onClick={handleEditClick}><Edit2 className="w-4 h-4 mr-2" /> Edit All</Button>
        ) : (
          <div className="flex gap-2">
            <Button variant="ghost" onClick={() => setIsEditing(false)}><X className="w-4 h-4 mr-2" /> Cancel</Button>
            <Button onClick={handleSave}><Save className="w-4 h-4 mr-2" /> Save All</Button>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Parking */}
        <Card>
          <CardHeader className="bg-muted/50 border-b pb-4">
            <CardTitle className="text-lg flex items-center"><Car className="w-5 h-5 mr-2 text-muted-foreground" /> Parking</CardTitle>
          </CardHeader>
          <CardContent className="p-4 space-y-3">
            {isEditing ? (
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1"><Label>Spaces</Label><Input value={editParking.spaces} onChange={e => setEditParking({ ...editParking, spaces: e.target.value })} /></div>
                  <div className="space-y-1"><Label>Spots</Label><Input value={editParking.spots} onChange={e => setEditParking({ ...editParking, spots: e.target.value })} /></div>
                  <div className="space-y-1 col-span-2"><Label>Type</Label><Input value={editParking.type} onChange={e => setEditParking({ ...editParking, type: e.target.value })} /></div>
                </div>
                <div className="space-y-1"><Label>Notes</Label><Textarea value={editParking.notes} onChange={e => setEditParking({ ...editParking, notes: e.target.value })} /></div>
              </div>
            ) : !parking.spaces && !parking.spots && !parking.type ? (
              <div className="text-muted-foreground text-sm py-4 text-center">No parking data.</div>
            ) : (
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div><p className="text-muted-foreground font-medium">Spaces</p><p className="font-semibold">{parking.spaces || "—"}</p></div>
                <div><p className="text-muted-foreground font-medium">Spots</p><p className="font-semibold">{parking.spots || "—"}</p></div>
                <div className="col-span-2"><p className="text-muted-foreground font-medium">Type</p><p>{parking.type || "—"}</p></div>
                {parking.notes && <div className="col-span-2"><p className="text-muted-foreground font-medium">Notes</p><p className="bg-muted p-2 rounded-md border text-sm mt-1">{parking.notes}</p></div>}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Pets */}
        <Card>
          <CardHeader className="bg-muted/50 border-b pb-4">
            <CardTitle className="text-lg flex items-center"><Dog className="w-5 h-5 mr-2 text-muted-foreground" /> Pets</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {isEditing ? (
              <div className="p-4 space-y-4">
                {editPets.map((pet, idx) => (
                  <div key={idx} className="space-y-2 p-3 border rounded-md relative bg-muted/30">
                    <Button variant="ghost" size="icon" className="absolute right-1 top-1 h-6 w-6 text-destructive" onClick={() => setEditPets(editPets.filter((_, i) => i !== idx))}><Trash2 className="w-4 h-4" /></Button>
                    <div className="grid grid-cols-2 gap-2">
                      <Input placeholder="Name" value={pet.name} onChange={e => { const p = [...editPets]; p[idx].name = e.target.value; setEditPets(p); }} />
                      <Input placeholder="Type" value={pet.type} onChange={e => { const p = [...editPets]; p[idx].type = e.target.value; setEditPets(p); }} />
                      <Input placeholder="Breed" value={pet.breed} onChange={e => { const p = [...editPets]; p[idx].breed = e.target.value; setEditPets(p); }} />
                      <Input placeholder="Weight" value={pet.weight} onChange={e => { const p = [...editPets]; p[idx].weight = e.target.value; setEditPets(p); }} />
                    </div>
                  </div>
                ))}
                <Button variant="outline" size="sm" onClick={() => setEditPets([...editPets, { name: "", type: "", breed: "", weight: "", notes: "", isNew: true }])} className="w-full"><Plus className="w-4 h-4 mr-2" /> Add Pet</Button>
              </div>
            ) : pets.length === 0 ? (
              <div className="p-6 text-center text-muted-foreground text-sm">No pets registered.</div>
            ) : (
              <div className="divide-y">
                {pets.map((pet, idx) => (
                  <div key={idx} className="p-4 space-y-1 text-sm">
                    <p className="font-semibold">{pet.name} <span className="text-muted-foreground font-normal">({pet.type})</span></p>
                    <p className="text-muted-foreground">{pet.breed} • {pet.weight}</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* General Info */}
        <Card className="md:col-span-2">
          <CardHeader className="bg-muted/50 border-b pb-4">
            <CardTitle className="text-lg flex items-center"><Info className="w-5 h-5 mr-2 text-muted-foreground" /> General Information</CardTitle>
          </CardHeader>
          <CardContent className="p-4">
            {isEditing ? (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-1"><Label>Utilities</Label><Textarea value={editGeneral.utilities} onChange={e => setEditGeneral({ ...editGeneral, utilities: e.target.value })} /></div>
                <div className="space-y-1"><Label>Amenities</Label><Textarea value={editGeneral.amenities} onChange={e => setEditGeneral({ ...editGeneral, amenities: e.target.value })} /></div>
                <div className="space-y-1"><Label>Restrictions</Label><Textarea value={editGeneral.restrictions} onChange={e => setEditGeneral({ ...editGeneral, restrictions: e.target.value })} /></div>
              </div>
            ) : !generalInfo.utilities && !generalInfo.amenities && !generalInfo.restrictions ? (
              <div className="text-muted-foreground text-sm py-2 text-center">No general information.</div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 text-sm">
                <div><p className="text-muted-foreground font-medium mb-1">Utilities</p><p>{generalInfo.utilities || "—"}</p></div>
                <div><p className="text-muted-foreground font-medium mb-1">Amenities</p><p>{generalInfo.amenities || "—"}</p></div>
                <div><p className="text-muted-foreground font-medium mb-1">Restrictions</p><p>{generalInfo.restrictions || "—"}</p></div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Occupants */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle className="text-lg flex items-center"><Users2 className="w-5 h-5 mr-2 text-muted-foreground" /> Other Occupants</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Relationship</TableHead>
                  <TableHead>Contact</TableHead>
                  {isEditing && <TableHead className="w-16" />}
                </TableRow>
              </TableHeader>
              <TableBody>
                {isEditing ? editOccupants.map((occ, idx) => (
                  <TableRow key={idx}>
                    <TableCell><Input value={occ.name} onChange={e => { const o = [...editOccupants]; o[idx].name = e.target.value; setEditOccupants(o); }} placeholder="Name *" /></TableCell>
                    <TableCell><Input value={occ.relationship} onChange={e => { const o = [...editOccupants]; o[idx].relationship = e.target.value; setEditOccupants(o); }} placeholder="Role *" /></TableCell>
                    <TableCell className="space-y-2">
                      <Input value={occ.email} onChange={e => { const o = [...editOccupants]; o[idx].email = e.target.value; setEditOccupants(o); }} placeholder="Email" />
                      <Input value={occ.phone} onChange={e => { const o = [...editOccupants]; o[idx].phone = e.target.value; setEditOccupants(o); }} placeholder="Phone" />
                    </TableCell>
                    <TableCell><Button variant="ghost" size="icon" className="text-destructive" onClick={() => setEditOccupants(editOccupants.filter((_, i) => i !== idx))}><Trash2 className="w-4 h-4" /></Button></TableCell>
                  </TableRow>
                )) : occupants.length === 0 ? (
                  <TableRow><TableCell colSpan={3} className="text-center text-muted-foreground py-8">No other occupants.</TableCell></TableRow>
                ) : occupants.map((occ, idx) => (
                  <TableRow key={idx}>
                    <TableCell className="font-medium">{occ.name}</TableCell>
                    <TableCell><Badge variant="secondary">{occ.relationship}</Badge></TableCell>
                    <TableCell>
                      <div className="text-sm">{occ.email || "—"}</div>
                      <div className="text-sm text-muted-foreground">{occ.phone || "—"}</div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {isEditing && (
              <div className="p-4 border-t bg-muted/50">
                <Button variant="outline" size="sm" onClick={() => setEditOccupants([...editOccupants, { name: "", relationship: "", phone: "", email: "", isNew: true }])} className="w-full border-dashed">
                  <Plus className="w-4 h-4 mr-2" /> Add Occupant
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
