"use client";

import { API_BASE_URL, getAuthHeaders } from "@/lib/api";
import React, { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Search, Building2, Loader2, Tag, Maximize2, DollarSign, ChevronRight, ExternalLink, Trash2 } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";

interface Asset {
    id: number;
    name: string;
    formatted_price: string;
    status: string;
    location: string;
    precise_size: string | number;
    is_available: boolean;
    asset_type_name: string;
}

export default function AssetsPage() {
    const router = useRouter();
    const [assets, setAssets] = useState<Asset[]>([]);
    const [properties, setProperties] = useState<any[]>([]);
    const [assetTypes, setAssetTypes] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);

    // Filters
    const [searchQuery, setSearchQuery] = useState("");
    const [statusFilter, setStatusFilter] = useState("all");

    // Delete state
    const [deleteTarget, setDeleteTarget] = useState<Asset | null>(null);
    const [isDeleting, setIsDeleting] = useState(false);

    // Dialog form
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({
        name: "",
        location: "",
        precise_size: "",
        price: "",
        property: "",
        asset_type: "",
        status: "available",
    });

    // Estate Dialog form
    const [isEstateDialogOpen, setIsEstateDialogOpen] = useState(false);
    const [isSubmittingEstate, setIsSubmittingEstate] = useState(false);
    const [estateFormData, setEstateFormData] = useState({
        name: "",
        location: "",
    });

    const fetchAll = () => {
        setLoading(true);
        Promise.all([
            fetch(`${API_BASE_URL}/assets/`, { headers: getAuthHeaders() }).then(res => res.json()),
            fetch(`${API_BASE_URL}/properties/`, { headers: getAuthHeaders() }).then(res => res.json()),
            fetch(`${API_BASE_URL}/asset-types/`, { headers: getAuthHeaders() }).then(res => res.json())
        ])
            .then(([assetsData, propsData, typesData]) => {
                setAssets(assetsData.results || assetsData);
                setProperties(propsData.results || propsData);
                setAssetTypes(typesData.results || typesData);
                setLoading(false);
            })
            .catch(err => {
                console.error("Fetch err:", err);
                setLoading(false);
            });
    };

    useEffect(() => {
        fetchAll();
    }, []);

    const handleAddAsset = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/assets/`, {
                method: "POST",
                headers: getAuthHeaders(),
                body: JSON.stringify(formData)
            });
            if (res.ok) {
                setIsDialogOpen(false);
                setFormData({ name: "", location: "", precise_size: "", price: "", property: "", asset_type: "", status: "available" });
                fetchAll();
            } else {
                console.error("Failed:", await res.text());
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleAddEstate = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmittingEstate(true);
        try {
            const res = await fetch(`${API_BASE_URL}/properties/`, {
                method: "POST",
                headers: getAuthHeaders(),
                body: JSON.stringify(estateFormData)
            });
            if (res.ok) {
                setIsEstateDialogOpen(false);
                setEstateFormData({ name: "", location: "" });
                fetchAll();
            } else {
                console.error("Failed:", await res.text());
            }
        } catch (err) {
            console.error(err);
        } finally {
            setIsSubmittingEstate(false);
        }
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'available':
                return <Badge className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-none px-2.5 py-0.5 font-bold text-[10px] tracking-widest uppercase rounded-full">Available</Badge>;
            case 'reserved':
                return <Badge className="bg-amber-500/10 text-amber-600 dark:text-amber-400 border-none px-2.5 py-0.5 font-bold text-[10px] tracking-widest uppercase rounded-full">Reserved</Badge>;
            case 'under_contract':
                return <Badge className="bg-sky-500/10 text-sky-600 dark:text-sky-400 border-none px-2.5 py-0.5 font-bold text-[10px] tracking-widest uppercase rounded-full">Under Contract</Badge>;
            case 'completed':
                return <Badge className="bg-muted/40 text-muted-foreground border-none px-2.5 py-0.5 font-bold text-[10px] tracking-widest uppercase rounded-full">Sold</Badge>;
            default:
                return <Badge variant="outline" className="border-border/20 font-bold text-[10px] uppercase tracking-widest rounded-full">{status}</Badge>;
        }
    };

    const deleteAsset = async () => {
        if (!deleteTarget) return;
        setIsDeleting(true);
        try {
            const res = await fetch(`${API_BASE_URL}/assets/${deleteTarget.id}/`, {
                method: "DELETE",
                headers: getAuthHeaders(),
            });
            if (res.ok || res.status === 204) {
                setAssets(prev => prev.filter(a => a.id !== deleteTarget.id));
                setDeleteTarget(null);
            } else {
                alert("Delete failed: " + (await res.text()));
            }
        } catch (e) {
            alert("Network error");
        } finally {
            setIsDeleting(false);
        }
    };

    // Client-side filtering
    const filteredAssets = assets.filter(asset => {
        const matchesSearch = asset.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
            (asset.location && asset.location.toLowerCase().includes(searchQuery.toLowerCase()));
        const matchesStatus = statusFilter === "all" || asset.status === statusFilter;
        return matchesSearch && matchesStatus;
    });

    return (
        <>
            <div className="flex-1 space-y-6 pb-12">
                {/* Header */}
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-3xl font-black tracking-tight text-foreground">Properties & Assets</h2>
                        <p className="text-muted-foreground mt-1 text-sm font-medium">
                            {assets.length} total plots · {assets.filter(a => a.is_available).length} available
                        </p>
                    </div>

                    <div className="flex gap-2">
                        <Dialog open={isEstateDialogOpen} onOpenChange={setIsEstateDialogOpen}>
                            <DialogTrigger asChild>
                                <Button variant="outline" className="border-border/20 bg-background font-bold text-xs rounded-xl hover:bg-muted/50 h-10 px-5">
                                    + Add Estate
                                </Button>
                            </DialogTrigger>
                            <DialogContent className="sm:max-w-[425px]">
                                <DialogHeader>
                                    <DialogTitle>Add New Estate / Property</DialogTitle>
                                </DialogHeader>
                                <form onSubmit={handleAddEstate} className="space-y-4 py-4">
                                    <div className="space-y-2">
                                        <Label>Estate Name</Label>
                                        <Input required value={estateFormData.name} onChange={e => setEstateFormData({ ...estateFormData, name: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>General Location</Label>
                                        <Input required value={estateFormData.location} onChange={e => setEstateFormData({ ...estateFormData, location: e.target.value })} />
                                    </div>
                                    <DialogFooter className="pt-4">
                                        <Button type="button" variant="outline" onClick={() => setIsEstateDialogOpen(false)}>Cancel</Button>
                                        <Button type="submit" disabled={isSubmittingEstate}>
                                            {isSubmittingEstate ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} Save Estate
                                        </Button>
                                    </DialogFooter>
                                </form>
                            </DialogContent>
                        </Dialog>

                        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                            <DialogTrigger asChild>
                                <Button className="bg-primary hover:bg-primary/90 text-primary-foreground font-bold text-xs rounded-xl px-5 h-10 shadow-lg shadow-primary/20">
                                    + Register Plot
                                </Button>
                            </DialogTrigger>
                            <DialogContent className="sm:max-w-[425px]">
                                <DialogHeader>
                                    <DialogTitle>Register Plot / Asset</DialogTitle>
                                </DialogHeader>
                                <form onSubmit={handleAddAsset} className="space-y-4 py-4">
                                    <div className="space-y-2">
                                        <Label>Name / Plot Number</Label>
                                        <Input required value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Location</Label>
                                        <Input required value={formData.location} onChange={e => setFormData({ ...formData, location: e.target.value })} placeholder="e.g. Lagos, Nigeria" />
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <Label>Size (sqm)</Label>
                                            <Input type="number" step="0.01" required value={formData.precise_size} onChange={e => setFormData({ ...formData, precise_size: e.target.value })} />
                                        </div>
                                        <div className="space-y-2">
                                            <Label>Price (₦)</Label>
                                            <Input type="number" step="0.01" required value={formData.price} onChange={e => setFormData({ ...formData, price: e.target.value })} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-2">
                                            <Label>Parent Estate</Label>
                                            <Select required value={formData.property} onValueChange={v => setFormData({ ...formData, property: v })}>
                                                <SelectTrigger><SelectValue placeholder="Estate..." /></SelectTrigger>
                                                <SelectContent>
                                                    {properties.map(p => <SelectItem key={p.id} value={String(p.id)}>{p.name}</SelectItem>)}
                                                </SelectContent>
                                            </Select>
                                        </div>
                                        <div className="space-y-2">
                                            <Label>Plot Type</Label>
                                            <Select required value={formData.asset_type} onValueChange={v => setFormData({ ...formData, asset_type: v })}>
                                                <SelectTrigger><SelectValue placeholder="Type..." /></SelectTrigger>
                                                <SelectContent>
                                                    {assetTypes.map(t => <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>)}
                                                </SelectContent>
                                            </Select>
                                        </div>
                                    </div>
                                    <DialogFooter className="pt-4">
                                        <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>Cancel</Button>
                                        <Button type="submit" disabled={isSubmitting}>
                                            {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null} Save Plot
                                        </Button>
                                    </DialogFooter>
                                </form>
                            </DialogContent>
                        </Dialog>
                    </div>
                </div>

                {/* Filter Bar */}
                <div className="flex flex-col sm:flex-row gap-3">
                    <div className="relative flex-1">
                        <Search className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            placeholder="Search by name or location..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="pl-11 bg-card border-border/20 rounded-xl h-11"
                        />
                    </div>
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                        <SelectTrigger className="w-full sm:w-[200px] bg-card border-border/20 rounded-xl h-11 font-medium">
                            <SelectValue placeholder="All Statuses" />
                        </SelectTrigger>
                        <SelectContent className="rounded-xl">
                            <SelectItem value="all">All Statuses</SelectItem>
                            <SelectItem value="available">Available</SelectItem>
                            <SelectItem value="reserved">Reserved</SelectItem>
                            <SelectItem value="under_contract">Under Contract</SelectItem>
                            <SelectItem value="completed">Sold</SelectItem>
                        </SelectContent>
                    </Select>
                </div>

                {/* Asset Table */}
                {loading ? (
                    <div className="h-64 flex items-center justify-center">
                        <Loader2 className="h-8 w-8 animate-spin text-primary/40" />
                    </div>
                ) : (
                    <Card className="rounded-2xl shadow-card border-none bg-card overflow-hidden">
                        {/* Table Header */}
                        <div className="hidden md:grid grid-cols-[2fr_1fr_1fr_1fr_1fr_40px] gap-4 px-6 py-3 border-b border-border/10 bg-muted/30">
                            <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Name</span>
                            <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Status</span>
                            <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground flex items-center gap-1"><Tag className="w-3 h-3" /> Type</span>
                            <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground flex items-center gap-1"><Maximize2 className="w-3 h-3" /> Size</span>
                            <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground flex items-center gap-1"><DollarSign className="w-3 h-3" /> Price</span>
                            <span></span>
                        </div>

                        {/* Rows */}
                        <div className="divide-y divide-border/10">
                            {filteredAssets.map((asset) => (
                                <Link
                                    href={`/assets/${asset.id}`}
                                    key={asset.id}
                                    className="grid grid-cols-1 md:grid-cols-[2fr_1fr_1fr_1fr_1fr_80px] gap-3 md:gap-4 items-center px-6 py-4 hover:bg-muted/20 transition-colors group cursor-pointer"
                                >
                                    {/* Name */}
                                    <div className="flex items-center gap-3">
                                        <div className="h-9 w-9 rounded-xl bg-primary/10 flex items-center justify-center shrink-0 group-hover:bg-primary/20 transition-colors">
                                            <Building2 className="h-4 w-4 text-primary" />
                                        </div>
                                        <div>
                                            <p className="font-bold text-sm text-foreground group-hover:text-primary transition-colors">{asset.name}</p>
                                            <p className="text-xs text-muted-foreground truncate max-w-[180px]">{asset.location || "—"}</p>
                                        </div>
                                    </div>

                                    {/* Status */}
                                    <div className="flex items-center">
                                        {getStatusBadge(asset.status)}
                                    </div>

                                    {/* Type */}
                                    <div className="text-sm text-muted-foreground font-medium">
                                        {asset.asset_type_name || <span className="text-border">—</span>}
                                    </div>

                                    {/* Size */}
                                    <div className="text-sm font-medium text-foreground">
                                        {asset.precise_size ? `${asset.precise_size} sqm` : <span className="text-muted-foreground">—</span>}
                                    </div>

                                    {/* Price */}
                                    <div className="text-sm font-black text-primary">
                                        {asset.formatted_price}
                                    </div>

                                    {/* View + Delete buttons */}
                                    <div className="hidden md:flex items-center justify-end gap-1">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-8 px-3 text-[10px] font-bold uppercase tracking-wider text-muted-foreground hover:text-primary hover:bg-primary/5 rounded-lg transition-all"
                                            onClick={(e) => e.stopPropagation()}
                                            asChild
                                        >
                                            <span>
                                                <ExternalLink className="h-3 w-3 mr-1.5" />
                                                View
                                            </span>
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="h-8 w-8 p-0 rounded-lg text-muted-foreground hover:text-rose-500 hover:bg-rose-500/10 transition-all"
                                            onClick={(e) => { e.preventDefault(); e.stopPropagation(); setDeleteTarget(asset); }}
                                        >
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </Button>
                                    </div>
                                </Link>
                            ))}

                            {filteredAssets.length === 0 && (
                                <div className="h-48 flex flex-col items-center justify-center text-muted-foreground gap-3">
                                    <Building2 className="w-10 h-10 opacity-20" />
                                    <p className="font-bold text-xs uppercase tracking-widest">No assets found</p>
                                    <p className="text-[11px]">Try adjusting your filters.</p>
                                </div>
                            )}
                        </div>
                    </Card>
                )}
            </div>

            {/* Delete Confirmation Dialog */}
            <Dialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
                <DialogContent className="sm:max-w-[400px] rounded-2xl">
                    <DialogHeader>
                        <DialogTitle className="text-rose-600 flex items-center gap-2">
                            <Trash2 className="h-5 w-5" /> Delete Asset
                        </DialogTitle>
                        <DialogDescription>
                            Permanently delete <strong>{deleteTarget?.name}</strong>? This cannot be undone and may affect linked contracts.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter className="gap-2 pt-2">
                        <Button variant="outline" className="rounded-xl" onClick={() => setDeleteTarget(null)}>Cancel</Button>
                        <Button variant="destructive" className="rounded-xl" onClick={deleteAsset} disabled={isDeleting}>
                            {isDeleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
                            Yes, Delete
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}


