import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { PortfolioTabs } from '@/components/portfolio/PortfolioTabs';
import { MovementModal } from '@/components/portfolio/MovementModal';
import { ReportHeader } from '@/components/portfolio/ReportHeader';
import { ExpiringTooltip } from '@/components/portfolio/ExpiringTooltip';
import { Building2, ChevronRight, Loader2 } from 'lucide-react';

type Loc = {
    location_id: number | null; name: string; units: number; occupied: number; vacant: number;
    occupancy_rate: number; expiring_soon: number; move_ins: number; move_outs: number; net: number;
};
type Totals = {
    locations: number; units: number; occupied: number; vacant: number;
    move_ins: number; move_outs: number; net: number; expiring_soon: number; occupancy_rate: number;
};
type Prev = { period: { start: string; end: string }; move_ins: number; move_outs: number; net: number };

function rateColor(rate: number) {
    if (rate >= 90) return 'text-emerald-600';
    if (rate >= 75) return 'text-foreground';
    return 'text-amber-600';
}

export default function Overview() {
    const props = usePage().props as unknown as {
        totals: Totals; locations: Loc[]; window: number; movement: number; seesAll: boolean;
        freshness?: any; expiringBreakdown?: any;
    };
    const { totals, locations, window: win, movement, seesAll, freshness, expiringBreakdown } = props;

    const [modal, setModal] = useState<{ title: string; location: string | null } | null>(null);


    return (
        <>
            <Head title="Portfolio" />
            <div className="mx-auto w-full max-w-6xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <Building2 className="size-5 text-primary" /> Portfolio
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {seesAll ? 'All locations' : 'Your assigned locations'} · live from Rentec
                    </p>
                </header>

                <PortfolioTabs />
                <ReportHeader freshness={freshness} />

                <div className="mb-5">
                    <label className="mb-1 block text-xs text-muted-foreground">Window</label>
                    <select value={win}
                        onChange={(e) => router.get('/portfolio', { window: e.target.value, movement }, { preserveState: true })}
                        className="rounded-md border border-border bg-background px-3 py-1.5 text-sm">
                        <option value={30}>Next 30 days</option>
                        <option value={60}>Next 60 days</option>
                        <option value={90}>Next 90 days</option>
                        <option value={180}>Next 180 days</option>
                        <option value={365}>Next 12 months</option>
                    </select>
                </div>

                <section className="mb-6 rounded-xl border border-border bg-accent/30 p-6">
                    <div className="mb-4 flex items-baseline justify-between">
                        <h2 className="font-semibold text-foreground">
                            Company Totals <span className="ml-2 text-sm font-normal text-muted-foreground">{totals.locations} locations</span>
                        </h2>
                        <div className="text-right">
                            <p className={`text-sm font-semibold ${rateColor(totals.occupancy_rate)}`}>{totals.occupancy_rate}% occupied</p>
                            <p className="text-xs"><ExpiringTooltip count={totals.expiring_soon} days={win} breakdown={expiringBreakdown} /></p>
                        </div>
                    </div>

                    <div className="grid grid-cols-3 gap-4 border-b border-border pb-4">
                        <Stat label="Units" value={totals.units} />
                        <Stat label="Occupied" value={totals.occupied} />
                        <Stat label="Vacant" value={totals.vacant} />
                    </div>
                    <div className="grid grid-cols-3 gap-4 pt-4">
                        <Stat label="Move-Ins" value={totals.move_ins} />
                        <Stat label="Move-Outs" value={totals.move_outs} />
                        <Stat label="Net" value={totals.net} signed />
                    </div>

                    <PrevBtn onClick={() => setModal({ title: 'All Locations', location: null })} days={movement} />
                </section>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {locations.map((l) => (
                        <div key={l.name} className="rounded-xl border border-border bg-card p-5 shadow-sm">
                            <div className="mb-3 flex items-start justify-between">
                                <p className="font-semibold text-foreground">{l.name}</p>
                                <div className="text-right">
                                    <p className={`text-xs font-semibold ${rateColor(l.occupancy_rate)}`}>{l.occupancy_rate}% occupied</p>
                                    <p className="text-[11px] text-amber-600">{l.expiring_soon} exp ≤ {win}d</p>
                                </div>
                            </div>
                            <div className="grid grid-cols-3 gap-2 border-b border-border pb-3">
                                <Mini label="Units" value={l.units} />
                                <Mini label="Occupied" value={l.occupied} />
                                <Mini label="Vacant" value={l.vacant} />
                            </div>
                            <div className="grid grid-cols-3 gap-2 pt-3">
                                <Mini label="Move-Ins" value={l.move_ins} />
                                <Mini label="Move-Outs" value={l.move_outs} />
                                <Mini label="Net" value={l.net} signed />
                            </div>
                            <PrevBtn onClick={() => setModal({ title: l.name, location: l.name })} days={movement} small />
                        </div>
                    ))}
                    {locations.length === 0 && (
                        <p className="col-span-3 rounded-xl border border-dashed border-border p-12 text-center text-sm text-muted-foreground">
                            No locations available. If you're not an administrator, ask to be assigned to a location.
                        </p>
                    )}
                </div>
            </div>
            {modal && <MovementModal title={modal.title} location={modal.location} onClose={() => setModal(null)} />}
        </>
    );
}

function PrevBtn({ onClick, days, small }: { onClick: () => void; days: number; small?: boolean }) {
    return (
        <button onClick={onClick}
            className={`mt-3 flex w-full items-center justify-end gap-0.5 border-t border-dashed border-border pt-2 ${small ? 'text-[11px]' : 'text-xs'} font-medium text-primary hover:underline`}>
            Prev {days} Day Net MI <ChevronRight className="size-3" />
        </button>
    );
}

function Stat({ label, value, signed }: { label: string; value: number; signed?: boolean }) {
    const color = signed ? (value > 0 ? 'text-emerald-600' : value < 0 ? 'text-destructive' : 'text-foreground') : 'text-foreground';
    return (
        <div className="text-center">
            <p className={`text-3xl font-semibold ${color}`}>{signed && value > 0 ? '+' : ''}{value.toLocaleString()}</p>
            <p className="mt-0.5 text-xs text-muted-foreground">{label}</p>
        </div>
    );
}

function Mini({ label, value, signed }: { label: string; value: number; signed?: boolean }) {
    const color = signed ? (value > 0 ? 'text-emerald-600' : value < 0 ? 'text-destructive' : 'text-foreground') : 'text-foreground';
    return (
        <div className="text-center">
            <p className={`text-lg font-semibold ${color}`}>{signed && value > 0 ? '+' : ''}{value}</p>
            <p className="text-[10px] text-muted-foreground">{label}</p>
        </div>
    );
}
