import { useState, useEffect, useRef } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Car, Search, Calendar, Clock, Trash2, ChevronUp, AlertCircle, Upload, RefreshCw } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
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 { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { format } from "date-fns";
import { useAuth } from "@/contexts/AuthContext";

const WARNING_LABELS: Record<string, string> = {
  first_warning: "1st Warning",
  second_warning: "2nd Warning",
  final_warning: "3rd & Final",
};

const WARNING_COLORS: Record<string, string> = {
  first_warning: "bg-amber-500 text-white",
  second_warning: "bg-orange-600 text-white",
  final_warning: "bg-destructive text-destructive-foreground",
};

const NEXT_LEVEL: Record<string, string> = {
  first_warning: "second_warning",
  second_warning: "final_warning",
};

export default function ParkingPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [records, setRecords] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [filterAssoc, setFilterAssoc] = useState("all");
  const [tab, setTab] = useState("list");

  // Log violation form
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [address, setAddress] = useState("");
  const [vehiclePlate, setVehiclePlate] = useState("");
  const [vehicleMake, setVehicleMake] = useState("");
  const [vehicleModel, setVehicleModel] = useState("");
  const [assocId, setAssocId] = useState("");
  const [photo, setPhoto] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  // Escalation
  const [escalateRecord, setEscalateRecord] = useState<any>(null);
  const [escalating, setEscalating] = useState(false);

  // Profile name
  const [profileName, setProfileName] = useState("");

  useEffect(() => {
    fetchData();
    fetchAssociations();
    fetchProfile();
  }, []);

  const fetchProfile = async () => {
    if (!user) return;
    const { data } = await supabase.from("profiles").select("full_name").eq("user_id", user.id).maybeSingle();
    if (data?.full_name) setProfileName(data.full_name);
  };

  const isBoardView = !!boardAssociationIds?.length;

  const fetchAssociations = async () => {
    let query = supabase.from("associations").select("id, name").eq("status", "active").order("name");
    if (isBoardView) query = query.in("id", boardAssociationIds!);
    const { data } = await query;
    setAssociations(data || []);
    if (data && data.length > 0 && !assocId) setAssocId(data[0].id);
  };

  const fetchData = async () => {
    setLoading(true);
    let query = supabase
      .from("parking_records")
      .select("*, associations(name)")
      .order("created_at", { ascending: false });
    if (isBoardView) query = query.in("association_id", boardAssociationIds!);
    const { data } = await query;
    setRecords(data || []);
    setLoading(false);
  };

  const filtered = records.filter((r) => {
    const matchesSearch =
      (r.title || "").toLowerCase().includes(search.toLowerCase()) ||
      (r.vehicle_plate || "").toLowerCase().includes(search.toLowerCase()) ||
      (r.vehicle_make || "").toLowerCase().includes(search.toLowerCase()) ||
      (r.address || "").toLowerCase().includes(search.toLowerCase());
    const matchesAssoc = filterAssoc === "all" || r.association_id === filterAssoc;
    return matchesSearch && matchesAssoc;
  });

  const handlePhotoSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setPhoto(f);
    setPhotoPreview(URL.createObjectURL(f));
  };

  const handleSubmit = async () => {
    if (!title.trim() || !assocId) {
      toast({ title: "Please fill in required fields", variant: "destructive" });
      return;
    }
    setSubmitting(true);
    let photoUrl: string | null = null;

    if (photo) {
      const ext = photo.name.split(".").pop();
      const path = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
      const { error: upErr } = await supabase.storage.from("parking-photos").upload(path, photo);
      if (!upErr) {
        const { data: urlData } = supabase.storage.from("parking-photos").getPublicUrl(path);
        photoUrl = urlData.publicUrl;
      }
    }

    const { error } = await supabase.from("parking_records").insert({
      association_id: assocId,
      title,
      description,
      address,
      vehicle_plate: vehiclePlate,
      vehicle_make: vehicleMake,
      vehicle_model: vehicleModel,
      photo_url: photoUrl,
      recorded_by: profileName || user?.email || "Unknown",
      warning_level: "first_warning",
      status: "open",
    });

    if (error) {
      toast({ title: "Error creating record", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Parking violation logged" });
      setTitle(""); setDescription(""); setAddress("");
      setVehiclePlate(""); setVehicleMake(""); setVehicleModel("");
      setPhoto(null); setPhotoPreview(null);
      setTab("list");
      fetchData();
    }
    setSubmitting(false);
  };

  const handleEscalate = async () => {
    if (!escalateRecord) return;
    const nextLevel = NEXT_LEVEL[escalateRecord.warning_level];
    if (!nextLevel) return;
    setEscalating(true);
    const { error } = await supabase
      .from("parking_records")
      .update({ warning_level: nextLevel })
      .eq("id", escalateRecord.id);
    if (error) {
      toast({ title: "Escalation failed", description: error.message, variant: "destructive" });
    } else {
      toast({ title: `Escalated to ${WARNING_LABELS[nextLevel]}` });
      fetchData();
    }
    setEscalating(false);
    setEscalateRecord(null);
  };

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from("parking_records").delete().eq("id", id);
    if (error) {
      toast({ title: "Delete failed", variant: "destructive" });
    } else {
      toast({ title: "Record deleted" });
      fetchData();
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Car className="h-6 w-6 text-primary" /> Parking Management
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Track unauthorized vehicles and manage warnings.</p>
        </div>
        <div className="flex items-center gap-2">
          <Select value={filterAssoc} onValueChange={setFilterAssoc}>
            <SelectTrigger className="w-48">
              <SelectValue placeholder="All Clients" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Clients</SelectItem>
              {associations.map((a) => (
                <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="ghost" size="icon" onClick={fetchData}>
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Tabs */}
      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="list">Records List</TabsTrigger>
          <TabsTrigger value="log">Log Violation</TabsTrigger>
        </TabsList>

        {/* Records List */}
        <TabsContent value="list" className="space-y-4 mt-4">
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input placeholder="Search by title, plate, make, address..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
          </div>

          {loading ? (
            <div className="flex justify-center py-12">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
            </div>
          ) : filtered.length === 0 ? (
            <Card>
              <CardContent className="py-12 text-center text-muted-foreground">No parking records found.</CardContent>
            </Card>
          ) : (
            <div className="space-y-4">
              {filtered.map((r) => (
                <Card key={r.id} className="overflow-hidden">
                  <div className="flex flex-col sm:flex-row">
                    {/* Photo */}
                    {r.photo_url ? (
                      <div className="sm:w-48 h-40 sm:h-auto flex-shrink-0">
                        <img src={r.photo_url} alt="Violation" className="w-full h-full object-cover" />
                      </div>
                    ) : (
                      <div className="sm:w-48 h-40 sm:h-auto flex-shrink-0 bg-muted flex items-center justify-center">
                        <Car className="h-10 w-10 text-muted-foreground/40" />
                      </div>
                    )}

                    {/* Details */}
                    <div className="flex-1 p-4 space-y-2">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex items-center gap-2 flex-wrap">
                          <Badge className={WARNING_COLORS[r.warning_level] || "bg-muted"}>
                            {WARNING_LABELS[r.warning_level] || r.warning_level}
                          </Badge>
                          <span className="text-xs text-muted-foreground">{r.associations?.name}</span>
                        </div>
                        <div className="flex items-center gap-1 flex-shrink-0">
                          {NEXT_LEVEL[r.warning_level] && (
                            <Button variant="outline" size="sm" className="text-amber-600 border-amber-300 hover:bg-amber-50" onClick={() => setEscalateRecord(r)}>
                              <ChevronUp className="h-3.5 w-3.5 mr-1" /> Escalate
                            </Button>
                          )}
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive" onClick={() => handleDelete(r.id)}>
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>

                      <h3 className="font-semibold text-foreground">{r.title}</h3>

                      <div className="flex flex-wrap gap-x-6 gap-y-1 text-sm text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Calendar className="h-3.5 w-3.5" />
                          {format(new Date(r.recorded_at), "MMM d, yyyy")}
                        </span>
                        <span className="flex items-center gap-1">
                          <Clock className="h-3.5 w-3.5" />
                          {format(new Date(r.recorded_at), "h:mm a")}
                        </span>
                      </div>

                      {(r.vehicle_plate || r.vehicle_make || r.vehicle_model) && (
                        <div className="flex items-center gap-2 text-sm">
                          <Car className="h-3.5 w-3.5 text-muted-foreground" />
                          <span className="font-medium">{r.vehicle_plate || "—"}</span>
                          <span className="text-muted-foreground">
                            {[r.vehicle_make, r.vehicle_model].filter(Boolean).join(" ") || "—"}
                          </span>
                        </div>
                      )}

                      {r.address && (
                        <p className="text-sm text-muted-foreground">{r.address}</p>
                      )}

                      <div className="flex items-center justify-between pt-1 text-xs text-muted-foreground">
                        <span>Recorded by {r.recorded_by || "Unknown"}</span>
                        <span>Added {format(new Date(r.created_at), "MMM d, h:mm a")}</span>
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>

        {/* Log Violation */}
        <TabsContent value="log" className="mt-4">
          <Card>
            <CardContent className="space-y-5">
              <h2 className="text-lg font-semibold text-foreground">Log New Parking Violation</h2>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Association *</Label>
                  <Select value={assocId} onValueChange={setAssocId}>
                    <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                    <SelectContent>
                      {associations.map((a) => (
                        <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Title / Citation *</Label>
                  <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Unauthorized vehicle in lot B" />
                </div>
                <div className="space-y-2">
                  <Label>Address</Label>
                  <Input value={address} onChange={(e) => setAddress(e.target.value)} placeholder="Location or address" />
                </div>
                <div className="space-y-2">
                  <Label>License Plate</Label>
                  <Input value={vehiclePlate} onChange={(e) => setVehiclePlate(e.target.value)} placeholder="e.g. ABC-1234" />
                </div>
                <div className="space-y-2">
                  <Label>Vehicle Make</Label>
                  <Input value={vehicleMake} onChange={(e) => setVehicleMake(e.target.value)} placeholder="e.g. Toyota" />
                </div>
                <div className="space-y-2">
                  <Label>Vehicle Model</Label>
                  <Input value={vehicleModel} onChange={(e) => setVehicleModel(e.target.value)} placeholder="e.g. Camry" />
                </div>
              </div>

              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Additional details about the violation..." rows={3} />
              </div>

              {/* Photo upload */}
              <div className="space-y-2">
                <Label>Photo Evidence</Label>
                <div
                  className="border-2 border-dashed border-border rounded-lg p-6 text-center cursor-pointer hover:border-primary/50 transition-colors"
                  onClick={() => fileRef.current?.click()}
                >
                  {photoPreview ? (
                    <img src={photoPreview} alt="Preview" className="mx-auto max-h-48 rounded-md object-contain" />
                  ) : (
                    <div className="space-y-2">
                      <Upload className="h-8 w-8 mx-auto text-muted-foreground" />
                      <p className="text-sm text-muted-foreground">Click to upload a photo</p>
                    </div>
                  )}
                  <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handlePhotoSelect} />
                </div>
              </div>

              <Button onClick={handleSubmit} disabled={submitting} className="w-full sm:w-auto">
                {submitting ? "Logging..." : "Log Violation"}
              </Button>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Escalation Dialog */}
      <Dialog open={!!escalateRecord} onOpenChange={(o) => !o && setEscalateRecord(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-amber-600">
              <AlertCircle className="h-5 w-5" /> Confirm Escalation
            </DialogTitle>
            <DialogDescription>
              Are you sure you want to escalate this parking violation?
            </DialogDescription>
          </DialogHeader>

          {escalateRecord && (
            <>
              <div className="flex items-center justify-between py-4 px-2">
                <div className="text-center p-3 bg-muted rounded-lg border w-2/5">
                  <span className="block text-xs text-muted-foreground uppercase font-semibold">Current</span>
                  <span className="font-medium">{WARNING_LABELS[escalateRecord.warning_level]}</span>
                </div>
                <span className="text-muted-foreground">→</span>
                <div className="text-center p-3 bg-destructive/10 rounded-lg border border-destructive/20 w-2/5">
                  <span className="block text-xs text-destructive uppercase font-semibold">Next</span>
                  <span className="font-bold text-destructive">
                    {WARNING_LABELS[NEXT_LEVEL[escalateRecord.warning_level]]}
                  </span>
                </div>
              </div>
              <div className="text-sm text-muted-foreground bg-muted p-3 rounded-md border">
                <p><strong>Vehicle:</strong> {escalateRecord.vehicle_plate || "N/A"} ({[escalateRecord.vehicle_make, escalateRecord.vehicle_model].filter(Boolean).join(" ") || "N/A"})</p>
                <p><strong>Title:</strong> {escalateRecord.title}</p>
              </div>
            </>
          )}

          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" onClick={() => setEscalateRecord(null)} disabled={escalating}>Cancel</Button>
            <Button variant="destructive" onClick={handleEscalate} disabled={escalating}>
              {escalating ? "Escalating..." : "Confirm Escalation"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
