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 { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { Edit2, Save, X, Plus, Trash2 } from "lucide-react";

interface Tenant {
  id: string;
  name: string;
  email: string | null;
  phone: string | null;
  lease_start: string | null;
  lease_end: string | null;
  status: string | null;
  isNew?: boolean;
}

export default function TenantsTab({ unitId }: { unitId: string }) {
  const { toast } = useToast();
  const [isEditing, setIsEditing] = useState(false);
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [editForm, setEditForm] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);

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

  const fetchTenants = async () => {
    const { data, error } = await supabase.from("unit_tenants").select("*").eq("unit_id", unitId);
    if (!error && data) setTenants(data);
    setLoading(false);
  };

  const handleChange = (index: number, field: string, value: string) => {
    const updated = [...editForm];
    (updated[index] as any)[field] = value;
    setEditForm(updated);
  };

  const handleSave = async () => {
    if (editForm.some(t => !t.name)) {
      toast({ title: "Validation Error", description: "Name is required.", variant: "destructive" });
      return;
    }
    try {
      for (const tenant of editForm) {
        const payload = { unit_id: unitId, name: tenant.name, email: tenant.email, phone: tenant.phone, lease_start: tenant.lease_start || null, lease_end: tenant.lease_end || null, status: tenant.status };
        if (tenant.isNew) await supabase.from("unit_tenants").insert([payload]);
        else await supabase.from("unit_tenants").update(payload).eq("id", tenant.id);
      }
      await fetchTenants();
      setIsEditing(false);
      toast({ title: "Success", description: "Tenants updated." });
    } catch (error) {
      console.error(error);
      toast({ title: "Error", description: "Failed to update tenants.", variant: "destructive" });
    }
  };

  const handleRemove = async (index: number) => {
    const tenant = editForm[index];
    if (!tenant.isNew) {
      await supabase.from("unit_tenants").delete().eq("id", tenant.id);
    }
    setEditForm(editForm.filter((_, i) => i !== index));
  };

  if (loading) return null;

  return (
    <Card className="border-border shadow-sm rounded-xl">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="text-lg">Current & Past Tenants</CardTitle>
        {!isEditing ? (
          <Button variant="outline" size="sm" onClick={() => { setEditForm([...tenants]); setIsEditing(true); }}>
            <Edit2 className="w-4 h-4 mr-2" /> Edit Tenants
          </Button>
        ) : (
          <div className="flex gap-2">
            <Button variant="ghost" size="sm" onClick={() => setIsEditing(false)}><X className="w-4 h-4 mr-2" /> Cancel</Button>
            <Button size="sm" onClick={handleSave}><Save className="w-4 h-4 mr-2" /> Save</Button>
          </div>
        )}
      </CardHeader>
      <CardContent className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead>Contact</TableHead>
              <TableHead>Lease Period</TableHead>
              <TableHead>Status</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isEditing ? (
              editForm.map((tenant, index) => (
                <TableRow key={tenant.id}>
                  <TableCell><Input value={tenant.name} onChange={e => handleChange(index, "name", e.target.value)} placeholder="Name *" /></TableCell>
                  <TableCell className="space-y-2">
                    <Input value={tenant.email ?? ""} onChange={e => handleChange(index, "email", e.target.value)} placeholder="Email" type="email" />
                    <Input value={tenant.phone ?? ""} onChange={e => handleChange(index, "phone", e.target.value)} placeholder="Phone" />
                  </TableCell>
                  <TableCell className="space-y-2">
                    <Input value={tenant.lease_start ?? ""} onChange={e => handleChange(index, "lease_start", e.target.value)} type="date" />
                    <Input value={tenant.lease_end ?? ""} onChange={e => handleChange(index, "lease_end", e.target.value)} type="date" />
                  </TableCell>
                  <TableCell>
                    <Select value={tenant.status ?? "active"} onValueChange={val => handleChange(index, "status", val)}>
                      <SelectTrigger className="w-24"><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="active">Active</SelectItem>
                        <SelectItem value="expired">Expired</SelectItem>
                      </SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" onClick={() => handleRemove(index)} className="text-destructive"><Trash2 className="w-4 h-4" /></Button>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              tenants.length === 0 ? (
                <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground py-8">No tenants recorded.</TableCell></TableRow>
              ) : (
                tenants.map(tenant => (
                  <TableRow key={tenant.id}>
                    <TableCell className="font-medium text-primary">{tenant.name}</TableCell>
                    <TableCell>
                      <div className="text-sm">{tenant.email || "—"}</div>
                      <div className="text-sm text-muted-foreground">{tenant.phone || "—"}</div>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">{tenant.lease_start || "N/A"} to {tenant.lease_end || "N/A"}</TableCell>
                    <TableCell>
                      <Badge variant={tenant.status === "active" ? "default" : "secondary"}>
                        {tenant.status?.toUpperCase() ?? "ACTIVE"}
                      </Badge>
                    </TableCell>
                    <TableCell />
                  </TableRow>
                ))
              )
            )}
          </TableBody>
        </Table>
        {isEditing && (
          <div className="p-4 border-t bg-muted/50">
            <Button variant="outline" size="sm" onClick={() => setEditForm([...editForm, { id: `temp-${Date.now()}`, name: "", email: "", phone: "", lease_start: "", lease_end: "", status: "active", isNew: true }])} className="w-full border-dashed">
              <Plus className="w-4 h-4 mr-2" /> Add Tenant
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
