import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { CheckCircle2, Loader2, Home, AlertTriangle, Lock, Plus, Trash2 } from "lucide-react";

type Vehicle = { make: string; model: string; year: string; color: string; plate: string };
type Pet = { type: string; breed: string; name: string; weight: string };
type Occupant = { name: string; relationship: string; age: string };

const emptyVehicle: Vehicle = { make: "", model: "", year: "", color: "", plate: "" };
const emptyPet: Pet = { type: "", breed: "", name: "", weight: "" };
const emptyOccupant: Occupant = { name: "", relationship: "", age: "" };

export default function TenantInfoSubmitPage() {
  const { token } = useParams<{ token: string }>();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [request, setRequest] = useState<any>(null);

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [emergencyName, setEmergencyName] = useState("");
  const [emergencyPhone, setEmergencyPhone] = useState("");
  const [leaseStart, setLeaseStart] = useState("");
  const [leaseEnd, setLeaseEnd] = useState("");
  const [leaseLength, setLeaseLength] = useState("");
  const [leaseFile, setLeaseFile] = useState<File | null>(null);
  const [vehicles, setVehicles] = useState<Vehicle[]>([{ ...emptyVehicle }]);
  const [pets, setPets] = useState<Pet[]>([]);
  const [occupants, setOccupants] = useState<Occupant[]>([]);
  const [notes, setNotes] = useState("");

  useEffect(() => {
    if (!token) return;
    (async () => {
      setLoading(true);
      const { data, error } = await supabase.rpc("lookup_tenant_info_request", { p_token: token });
      if (error || !data || data.length === 0) {
        setError("This link is invalid or could not be found.");
      } else {
        const row = data[0];
        if (row.submitted_at) {
          setError("This information has already been submitted. If you need to update it, please contact us.");
        } else if (new Date(row.expires_at) < new Date()) {
          setError("This link has expired. Please contact us to request a new submission link.");
        } else {
          setRequest(row);
        }
      }
      setLoading(false);
    })();
  }, [token]);

  const uploadLease = async (): Promise<string | null> => {
    if (!leaseFile || !request) return null;
    const ext = leaseFile.name.split(".").pop() || "pdf";
    const path = `tenant-info/${request.request_id}/lease-${Date.now()}.${ext}`;
    const { error: upErr } = await supabase.storage
      .from("public-form-attachments")
      .upload(path, leaseFile, { upsert: false });
    if (upErr) throw upErr;
    const { data: pub } = supabase.storage.from("public-form-attachments").getPublicUrl(path);
    return pub.publicUrl;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !request) return;
    if (!firstName.trim() || !lastName.trim()) {
      setError("Tenant first and last name are required.");
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      const leaseUrl = leaseFile ? await uploadLease() : null;
      const cleanedVehicles = vehicles.filter((v) => v.make || v.model || v.plate);
      const cleanedPets = pets.filter((p) => p.type || p.name);
      const cleanedOccupants = occupants.filter((o) => o.name);

      const { data, error: rpcErr } = await supabase.rpc("submit_tenant_info", {
        p_token: token,
        p_tenant_first_name: firstName.trim(),
        p_tenant_last_name: lastName.trim(),
        p_email: email.trim() || null,
        p_phone: phone.trim() || null,
        p_emergency_contact_name: emergencyName.trim() || null,
        p_emergency_contact_phone: emergencyPhone.trim() || null,
        p_lease_start: leaseStart || null,
        p_lease_end: leaseEnd || null,
        p_lease_length_months: leaseLength ? parseInt(leaseLength, 10) : null,
        p_lease_document_url: leaseUrl,
        p_vehicles: cleanedVehicles,
        p_pets: cleanedPets,
        p_occupants: cleanedOccupants,
        p_notes: notes.trim() || null,
      });
      if (rpcErr || data === false) {
        setError("Submission failed. The link may have expired. Please contact us.");
      } else {
        setSubmitted(true);
      }
    } catch (err: any) {
      setError("Could not upload document: " + (err?.message || "Unknown error"));
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20 p-4">
        <Card className="max-w-md w-full">
          <CardContent className="p-8 text-center space-y-4">
            <CheckCircle2 className="h-16 w-16 text-emerald-600 mx-auto" />
            <h2 className="text-2xl font-bold">Thank you!</h2>
            <p className="text-muted-foreground">Your tenant information has been received.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error && !request) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20 p-4">
        <Card className="max-w-md w-full">
          <CardContent className="p-8 text-center space-y-4">
            <AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
            <h2 className="text-xl font-bold">Unable to submit</h2>
            <p className="text-muted-foreground">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/20 py-10 px-4">
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <Home className="h-8 w-8 text-primary" />
              <div>
                <CardTitle>Tenant Information</CardTitle>
                <CardDescription>
                  {request?.property_address ? `For: ${request.property_address}` : "Rental property"}
                  {request?.association_name ? ` · ${request.association_name}` : ""}
                </CardDescription>
              </div>
            </div>
            <p className="text-xs text-muted-foreground flex items-center gap-1 mt-2">
              <Lock className="h-3 w-3" /> This is a secure submission.
            </p>
            {request?.custom_message && (
              <div className="mt-3 p-3 rounded-md bg-muted text-sm whitespace-pre-wrap">{request.custom_message}</div>
            )}
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-8">
              <section className="space-y-4">
                <h3 className="font-semibold text-base">Tenant</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div><Label>First Name *</Label><Input value={firstName} onChange={(e) => setFirstName(e.target.value)} required /></div>
                  <div><Label>Last Name *</Label><Input value={lastName} onChange={(e) => setLastName(e.target.value)} required /></div>
                  <div><Label>Email</Label><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /></div>
                  <div><Label>Phone</Label><Input value={phone} onChange={(e) => setPhone(e.target.value)} /></div>
                  <div><Label>Emergency Contact Name</Label><Input value={emergencyName} onChange={(e) => setEmergencyName(e.target.value)} /></div>
                  <div><Label>Emergency Contact Phone</Label><Input value={emergencyPhone} onChange={(e) => setEmergencyPhone(e.target.value)} /></div>
                </div>
              </section>

              <section className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-base">Additional Occupants</h3>
                  <Button type="button" variant="outline" size="sm" onClick={() => setOccupants([...occupants, { ...emptyOccupant }])}>
                    <Plus className="h-4 w-4 mr-1" /> Add Occupant
                  </Button>
                </div>
                {occupants.map((o, i) => (
                  <div key={i} className="grid grid-cols-1 md:grid-cols-[1fr_1fr_80px_auto] gap-2 items-end">
                    <div><Label className="text-xs">Name</Label><Input value={o.name} onChange={(e) => { const arr = [...occupants]; arr[i].name = e.target.value; setOccupants(arr); }} /></div>
                    <div><Label className="text-xs">Relationship</Label><Input value={o.relationship} onChange={(e) => { const arr = [...occupants]; arr[i].relationship = e.target.value; setOccupants(arr); }} /></div>
                    <div><Label className="text-xs">Age</Label><Input value={o.age} onChange={(e) => { const arr = [...occupants]; arr[i].age = e.target.value; setOccupants(arr); }} /></div>
                    <Button type="button" variant="ghost" size="icon" onClick={() => setOccupants(occupants.filter((_, idx) => idx !== i))}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                ))}
              </section>

              <section className="space-y-4">
                <h3 className="font-semibold text-base">Lease</h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div><Label>Lease Start</Label><Input type="date" value={leaseStart} onChange={(e) => setLeaseStart(e.target.value)} /></div>
                  <div><Label>Lease End</Label><Input type="date" value={leaseEnd} onChange={(e) => setLeaseEnd(e.target.value)} /></div>
                  <div><Label>Lease Length (months)</Label><Input type="number" min="1" value={leaseLength} onChange={(e) => setLeaseLength(e.target.value)} /></div>
                </div>
                <div>
                  <Label>Upload Lease Copy</Label>
                  <Input type="file" accept=".pdf,.png,.jpg,.jpeg,.doc,.docx" onChange={(e) => setLeaseFile(e.target.files?.[0] || null)} />
                </div>
              </section>

              <section className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-base">Vehicles</h3>
                  <Button type="button" variant="outline" size="sm" onClick={() => setVehicles([...vehicles, { ...emptyVehicle }])}>
                    <Plus className="h-4 w-4 mr-1" /> Add Vehicle
                  </Button>
                </div>
                {vehicles.map((v, i) => (
                  <div key={i} className="grid grid-cols-2 md:grid-cols-[1fr_1fr_80px_1fr_1fr_auto] gap-2 items-end">
                    <div><Label className="text-xs">Make</Label><Input value={v.make} onChange={(e) => { const arr = [...vehicles]; arr[i].make = e.target.value; setVehicles(arr); }} /></div>
                    <div><Label className="text-xs">Model</Label><Input value={v.model} onChange={(e) => { const arr = [...vehicles]; arr[i].model = e.target.value; setVehicles(arr); }} /></div>
                    <div><Label className="text-xs">Year</Label><Input value={v.year} onChange={(e) => { const arr = [...vehicles]; arr[i].year = e.target.value; setVehicles(arr); }} /></div>
                    <div><Label className="text-xs">Color</Label><Input value={v.color} onChange={(e) => { const arr = [...vehicles]; arr[i].color = e.target.value; setVehicles(arr); }} /></div>
                    <div><Label className="text-xs">License Plate</Label><Input value={v.plate} onChange={(e) => { const arr = [...vehicles]; arr[i].plate = e.target.value; setVehicles(arr); }} /></div>
                    <Button type="button" variant="ghost" size="icon" onClick={() => setVehicles(vehicles.filter((_, idx) => idx !== i))}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                ))}
              </section>

              <section className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-base">Pets</h3>
                  <Button type="button" variant="outline" size="sm" onClick={() => setPets([...pets, { ...emptyPet }])}>
                    <Plus className="h-4 w-4 mr-1" /> Add Pet
                  </Button>
                </div>
                {pets.map((p, i) => (
                  <div key={i} className="grid grid-cols-2 md:grid-cols-[1fr_1fr_1fr_100px_auto] gap-2 items-end">
                    <div><Label className="text-xs">Type (Dog/Cat)</Label><Input value={p.type} onChange={(e) => { const arr = [...pets]; arr[i].type = e.target.value; setPets(arr); }} /></div>
                    <div><Label className="text-xs">Breed</Label><Input value={p.breed} onChange={(e) => { const arr = [...pets]; arr[i].breed = e.target.value; setPets(arr); }} /></div>
                    <div><Label className="text-xs">Name</Label><Input value={p.name} onChange={(e) => { const arr = [...pets]; arr[i].name = e.target.value; setPets(arr); }} /></div>
                    <div><Label className="text-xs">Weight</Label><Input value={p.weight} onChange={(e) => { const arr = [...pets]; arr[i].weight = e.target.value; setPets(arr); }} /></div>
                    <Button type="button" variant="ghost" size="icon" onClick={() => setPets(pets.filter((_, idx) => idx !== i))}><Trash2 className="h-4 w-4" /></Button>
                  </div>
                ))}
              </section>

              <section>
                <Label>Notes (optional)</Label>
                <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} />
              </section>

              {error && <p className="text-sm text-destructive">{error}</p>}

              <Button type="submit" className="w-full" disabled={submitting}>
                {submitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
                Submit Tenant Information
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}