"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { SearchInput, DataPagination, StatusBadge, ConfirmDialog, TableSkeleton } from "@/components/shared";
import { useDataTable } from "@/hooks/use-data-table";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import type { Property, PropertyCategory, PaginatedResponse } from "@/lib/types";

export default function PropertiesPage() {
  const { page, search, setPage, setSearch, setFilter, searchParams } = useDataTable();
  const [data, setData] = useState<PaginatedResponse<Property> | null>(null);
  const [categories, setCategories] = useState<PropertyCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleteTarget, setDeleteTarget] = useState<Property | null>(null);

  const categoryFilter = searchParams.get("category") || "";
  const typeFilter = searchParams.get("type") || "";
  const statusFilter = searchParams.get("status") || "";

  const fetchProperties = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (categoryFilter) params.set("category", categoryFilter);
      if (typeFilter) params.set("type", typeFilter);
      if (statusFilter) params.set("status", statusFilter);
      params.set("page", String(page));
      params.set("per_page", "15");
      const { data: res } = await api.get(`/api/properties?${params}`);
      setData(res);
    } catch {
      toast.error("Failed to load properties");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    api.get("/api/properties/categories").then(({ data }) => setCategories(data.data)).catch(() => {});
  }, []);

  useEffect(() => {
    fetchProperties();
  }, [page, search, categoryFilter, typeFilter, statusFilter]);

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/api/properties/${deleteTarget.id}`);
      toast.success("Property deleted");
      fetchProperties();
    } catch {
      toast.error("Failed to delete property");
    }
  };

  const formatPrice = (price: number | null) => {
    if (!price) return "—";
    return new Intl.NumberFormat("en-KE", { style: "currency", currency: "KES", maximumFractionDigits: 0 }).format(price);
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-display text-2xl font-semibold">Properties</h1>
          <p className="text-sm text-muted-foreground">Manage property listings</p>
        </div>
        <Button asChild>
          <Link href="/dashboard/properties/create">
            <Plus className="mr-2 h-4 w-4" /> Add Property
          </Link>
        </Button>
      </div>

      <Card>
        <CardContent className="p-4">
          <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center">
            <SearchInput
              value={search}
              onChange={setSearch}
              placeholder="Search properties..."
              className="sm:max-w-xs"
            />
            <div className="flex flex-wrap gap-2">
              <Select value={categoryFilter} onValueChange={(v) => setFilter("category", v === "all" ? null : v)}>
                <SelectTrigger className="w-[140px]">
                  <SelectValue placeholder="Category" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Categories</SelectItem>
                  {categories.map((cat) => (
                    <SelectItem key={cat.id} value={cat.slug}>{cat.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={typeFilter} onValueChange={(v) => setFilter("type", v === "all" ? null : v)}>
                <SelectTrigger className="w-[120px]">
                  <SelectValue placeholder="Type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  <SelectItem value="sale">For Sale</SelectItem>
                  <SelectItem value="rent">For Rent</SelectItem>
                  <SelectItem value="lease">For Lease</SelectItem>
                </SelectContent>
              </Select>
              <Select value={statusFilter} onValueChange={(v) => setFilter("status", v === "all" ? null : v)}>
                <SelectTrigger className="w-[120px]">
                  <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="published">Published</SelectItem>
                  <SelectItem value="draft">Draft</SelectItem>
                  <SelectItem value="sold">Sold</SelectItem>
                  <SelectItem value="rented">Rented</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {loading ? (
            <TableSkeleton columns={6} rows={5} />
          ) : (
            <>
              <div className="overflow-x-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Property</TableHead>
                      <TableHead className="hidden md:table-cell">Category</TableHead>
                      <TableHead className="hidden sm:table-cell">Price</TableHead>
                      <TableHead className="hidden lg:table-cell">Location</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="w-[100px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data?.data.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} className="py-8 text-center text-muted-foreground">
                          No properties found
                        </TableCell>
                      </TableRow>
                    )}
                    {data?.data.map((property) => (
                      <TableRow key={property.id}>
                        <TableCell>
                          <div className="flex items-center gap-3">
                            {property.images?.[0]?.thumbnail ? (
                              <img
                                src={property.images[0].thumbnail}
                                alt={property.title}
                                className="h-10 w-14 rounded-md object-cover"
                              />
                            ) : (
                              <div className="flex h-10 w-14 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
                                No img
                              </div>
                            )}
                            <div>
                              <p className="font-medium line-clamp-1">{property.title}</p>
                              <p className="text-xs text-muted-foreground capitalize">{property.listing_type}</p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell className="hidden md:table-cell">
                          {property.category?.name || "—"}
                        </TableCell>
                        <TableCell className="hidden sm:table-cell font-medium">
                          {formatPrice(property.price as number | null)}
                        </TableCell>
                        <TableCell className="hidden lg:table-cell">
                          {[property.city, property.county].filter(Boolean).join(", ") || "—"}
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={property.status} />
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Button variant="ghost" size="sm" asChild className="h-8 w-8 p-0">
                              <Link href={`/dashboard/properties/${property.id}/edit`}>
                                <Pencil className="h-3.5 w-3.5" />
                              </Link>
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                              onClick={() => setDeleteTarget(property)}
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {data && (
                <div className="mt-4">
                  <DataPagination
                    currentPage={data.meta.current_page}
                    lastPage={data.meta.last_page}
                    onPageChange={setPage}
                    total={data.meta.total}
                    from={data.meta.from}
                    to={data.meta.to}
                  />
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
        onConfirm={handleDelete}
        title="Delete Property"
        description={`Are you sure you want to delete "${deleteTarget?.title}"? This action cannot be undone.`}
      />
    </div>
  );
}
