import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
    Cloud, CloudOff, RefreshCw, Download, AlertTriangle,
    CheckCircle, Clock, MapPin, ArrowUpDown,
    FileText, ExternalLink, Filter, Box
} from 'lucide-react';
import { metrcApi, MetrcReportResponse, MetrcAuditResponse } from '../lib/metrcApi';
import { PageHeader, EmptyState, MetricCard } from '../components/ui/LinearPrimitives';
import { DataTable, Column } from '../components/ui/DataTable';
import { cn } from '../lib/utils';

// --- Configuration ---

const SEVERITY_CONFIG = {
    CRITICAL: { color: 'text-[var(--color-error)] bg-[var(--color-error)]/10', label: 'Critical' },
    HIGH: { color: 'text-[var(--color-warning)] bg-[var(--color-warning)]/10', label: 'High' },
    MEDIUM: { color: 'text-yellow-500 bg-yellow-500/10', label: 'Medium' },
    LOW: { color: 'text-[var(--color-accent)] bg-[var(--color-accent)]/10', label: 'Low' }
};

// --- Page Component ---

export default function MetrcDashboardPage() {
    const [loading, setLoading] = useState(true);
    const [syncing, setSyncing] = useState(false);
    const [report, setReport] = useState<MetrcReportResponse | null>(null);
    const [audit, setAudit] = useState<MetrcAuditResponse | null>(null);
    const [activeTab, setActiveTab] = useState<'overview' | 'plants' | 'audit'>('overview');
    const [searchTerm, setSearchTerm] = useState('');
    const [lastSync, setLastSync] = useState<Date | null>(null);
    const [selectedHistoryPlant, setSelectedHistoryPlant] = useState<any | null>(null);

    useEffect(() => {
        loadData();
    }, []);

    async function loadData() {
        setLoading(true);
        try {
            const [reportData, auditData] = await Promise.all([
                metrcApi.getReport(),
                metrcApi.getAuditReport()
            ]);
            setReport(reportData);
            setAudit(auditData);
        } catch (error) {
            console.error('Failed to load METRC data:', error);
        } finally {
            setLoading(false);
        }
    }

    async function handleSync() {
        setSyncing(true);
        try {
            const result = await metrcApi.syncAll();
            if (result.success) {
                setLastSync(new Date());
                await loadData();
            }
        } catch (error) {
            console.error('Sync failed:', error);
        } finally {
            setSyncing(false);
        }
    }

    async function handleExportCsv() {
        try {
            const csv = await metrcApi.exportCsv();
            metrcApi.downloadCsv(csv);
        } catch (error) {
            console.error('Export failed:', error);
        }
    }

    const filteredPlants = report?.plants.filter((p: any) =>
        searchTerm === '' ||
        p.tagNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        p.room.toLowerCase().includes(searchTerm.toLowerCase())
    ) || [];

    // --- Table Column Definitions ---

    const plantColumns: Column<any>[] = [
        {
            key: 'tagNumber',
            header: 'Plant Tag',
            cell: (plant) => (
                <div className="flex flex-col">
                    <span className="font-mono text-xs font-bold text-[var(--color-text-primary)]">{plant.tagNumber}</span>
                    <span className="text-[10px] text-indigo-500 font-medium">METRC ID</span>
                </div>
            )
        },
        {
            key: 'location',
            header: 'METRC Location',
            cell: (plant) => <span className="text-xs font-mono text-[var(--color-text-tertiary)]">{plant.location || '—'}</span>
        },
        {
            key: 'room',
            header: 'Local Room',
            cell: (plant) => <span className="text-sm text-[var(--color-text-secondary)]">{plant.room}</span>
        },
        {
            key: 'status',
            header: 'Status',
            className: 'text-center',
            cell: () => (
                <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-[var(--color-primary)]/10 text-[var(--color-primary)]">
                    <CheckCircle size={10} />
                    Synced
                </span>
            )
        },
        {
            key: 'actions',
            header: '',
            className: 'text-right',
            cell: (plant) => (
                <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button
                        onClick={(e) => { e.stopPropagation(); setSelectedHistoryPlant(plant); }}
                        className="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-md text-[var(--color-text-tertiary)]"
                    >
                        <Clock size={14} />
                    </button>
                    <Link
                        to={`/facility/3d?plant=${plant.tagNumber}`}
                        className="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-md text-indigo-500"
                    >
                        <Box size={14} />
                    </Link>
                </div>
            )
        }
    ];

    const auditColumns: Column<any>[] = [
        {
            key: 'plantTag',
            header: 'Plant Tag',
            cell: (move) => <span className="font-mono text-xs font-bold">{move.plantTag}</span>
        },
        {
            key: 'from',
            header: 'Previous Room',
            cell: (move) => <span className="text-[var(--color-text-tertiary)]">{move.from}</span>
        },
        {
            key: 'to',
            header: 'New Room',
            cell: (move) => <span className="text-indigo-500 font-medium">{move.to}</span>
        },
        {
            key: 'movedAt',
            header: 'Timestamp',
            cell: (move) => (
                <div className="flex flex-col">
                    <span className="text-xs">{new Date(move.movedAt).toLocaleDateString()}</span>
                    <span className="text-[10px] text-[var(--color-text-tertiary)]">{new Date(move.movedAt).toLocaleTimeString()}</span>
                </div>
            )
        }
    ];

    return (
        <div className="space-y-8 animate-in fade-in duration-500">
            <PageHeader
                title="METRC Compliance"
                subtitle="The authoritative state sync interface for facility compliance."
                actions={
                    <div className="flex gap-2">
                        <button
                            onClick={handleSync}
                            disabled={syncing}
                            className="btn btn-secondary shadow-sm"
                        >
                            <RefreshCw size={16} className={syncing ? "animate-spin" : ""} />
                            Sync All
                        </button>
                        <button
                            onClick={handleExportCsv}
                            className="btn btn-primary shadow-lg shadow-indigo-500/20"
                        >
                            <Download size={16} />
                            Export CSV
                        </button>
                    </div>
                }
            />

            {/* Connection Banner */}
            <div className="p-4 rounded-xl border border-amber-500/20 bg-[var(--color-warning)]/5 flex items-center gap-4">
                <div className="w-10 h-10 rounded-full bg-[var(--color-warning)]/10 flex items-center justify-center text-[var(--color-warning)]">
                    <CloudOff size={20} />
                </div>
                <div className="flex-1">
                    <h4 className="text-sm font-bold text-amber-900 dark:text-amber-200">Sandbox / Demo Environment</h4>
                    <p className="text-xs text-[var(--color-warning)]">The METRC production API is disabled. You are viewing simulated system data.</p>
                </div>
                <a href="https://api-ca.metrc.com" target="_blank" rel="noreferrer" className="text-xs font-bold text-amber-600 hover:underline flex items-center gap-1">
                    API Docs <ExternalLink size={12} />
                </a>
            </div>

            {/* Metrics */}
            {report && (
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <MetricCard icon={Box} label="Active Tags" value={report.plantCount.toLocaleString()} accent="accent" />
                    <MetricCard icon={ArrowUpDown} label="Total Moves" value={audit?.summary.totalMoves || 0} accent="accent" />
                    <MetricCard icon={CheckCircle} label="Success Rate" value="100%" accent="success" />
                    <MetricCard icon={AlertTriangle} label="Issues" value="0" accent="success" />
                </div>
            )}

            {/* Tabs */}
            <div className="flex items-center gap-1 p-1 bg-[var(--color-bg-tertiary)] rounded-xl w-fit">
                {['overview', 'plants', 'audit'].map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab as any)}
                        className={cn(
                            "px-6 py-2 rounded-lg text-xs font-bold uppercase tracking-widest transition-all",
                            activeTab === tab
                                ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] shadow-sm"
                                : "text-[var(--color-text-tertiary)] hover:text-slate-600 dark:hover:text-slate-200"
                        )}
                    >
                        {tab}
                    </button>
                ))}
            </div>

            {/* Tab Content */}
            {activeTab === 'overview' && (
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <div className="space-y-4">
                        <h3 className="text-sm font-bold text-[var(--color-text-tertiary)] uppercase tracking-widest px-2">Recent Compliance Events</h3>
                        <DataTable
                            data={audit?.recentMoves.slice(0, 5) || []}
                            columns={auditColumns}
                            isLoading={loading}
                        />
                    </div>
                    <div className="card p-6 flex flex-col justify-center items-center text-center space-y-4 border-dashed border-2">
                        <div className="w-16 h-16 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center text-[var(--color-primary)]">
                            <CheckCircle size={32} />
                        </div>
                        <div>
                            <h3 className="text-lg font-bold">System in Sync</h3>
                            <p className="text-sm text-[var(--color-text-tertiary)]">No discrepancies detected between local state and METRC tracking ID logs.</p>
                        </div>
                        <button className="btn btn-secondary btn-sm">Download Full Reconciliation Report</button>
                    </div>
                </div>
            )}

            {activeTab === 'plants' && (
                <div className="space-y-4">
                    <div className="flex gap-4">
                        <div className="relative flex-1">
                            <Filter className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-tertiary)]" size={16} />
                            <input
                                placeholder="Filter by Tag ID or Room Name..."
                                className="input pl-10 h-10 w-full"
                                value={searchTerm}
                                onChange={e => setSearchTerm(e.target.value)}
                            />
                        </div>
                    </div>
                    <DataTable
                        data={filteredPlants}
                        columns={plantColumns}
                        isLoading={loading}
                        emptyState={
                            <EmptyState icon={MapPin} title="No plants found" description="Try adjusting your search or filters." />
                        }
                    />
                </div>
            )}

            {activeTab === 'audit' && (
                <div className="space-y-4">
                    <DataTable
                        data={audit?.recentMoves || []}
                        columns={auditColumns}
                        isLoading={loading}
                    />
                </div>
            )}

            {/* History Modal placeholder (Styled) */}
            {selectedHistoryPlant && (
                <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-md z-[100] flex items-center justify-center p-4" onClick={() => setSelectedHistoryPlant(null)}>
                    <div className="bg-white dark:bg-[#0A0A0A] border border-[var(--color-border-subtle)] rounded-2xl shadow-2xl max-w-lg w-full p-8 animate-in zoom-in" onClick={e => e.stopPropagation()}>
                        <div className="text-center space-y-4">
                            <div className="w-12 h-12 rounded-full bg-indigo-500/10 flex items-center justify-center text-indigo-500 mx-auto">
                                <Clock size={24} />
                            </div>
                            <h3 className="text-xl font-bold">Plant Lifecycle History</h3>
                            <p className="text-sm text-[var(--color-text-tertiary)]">Tracking history for <span className="font-mono font-bold text-[var(--color-text-primary)]">{selectedHistoryPlant.tagNumber}</span></p>
                            <div className="py-8 border-y border-dashed">
                                {/* Simplified timeline */}
                                <p className="text-xs text-[var(--color-text-tertiary)] italic">Historical chain-of-custody logs are being processed...</p>
                            </div>
                            <button onClick={() => setSelectedHistoryPlant(null)} className="btn btn-primary w-full">Close View</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
