import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Plus, MoveRight, Sprout, Leaf, Flower, Archive, Scale, ClipboardList, Bug, Search, ChevronRight, Calendar, Cloud, CloudOff, CheckCircle } from 'lucide-react';
import { Batch, batchesApi } from '../lib/batchesApi';
import { useToast } from '../context/ToastContext';
import BatchTransitionModal from '../components/BatchTransitionModal';
import WeightLogModal from '../components/WeightLogModal';
import CreateTaskModal from '../components/tasks/CreateTaskModal';
import IPMScheduleModal from '../components/IPMScheduleModal';
import ScoutingModal from '../components/ipm/ScoutingModal';
import { PullToRefresh } from '../components/ui/PullToRefresh';
import { QuickLogBar } from '../components/touchpoints/QuickLogButtons';
import { PageHeader, SectionHeader, EmptyState, ActionButton, CardSkeleton } from '../components/ui/LinearPrimitives';

const STAGE_CONFIG = {
    CLONE_IN: { label: 'Clone', icon: Sprout, color: 'bg-blue-500', order: 0 },
    VEGETATIVE: { label: 'Veg', icon: Leaf, color: 'bg-green-500', order: 1 },
    FLOWERING: { label: 'Flower', icon: Flower, color: 'bg-purple-500', order: 2 },
    HARVEST: { label: 'Harvest', icon: Archive, color: 'bg-amber-500', order: 3 },
    DRYING: { label: 'Dry', icon: Archive, color: 'bg-orange-500', order: 4 },
    CURING: { label: 'Cure', icon: Archive, color: 'bg-stone-500', order: 5 },
    FINISHED: { label: 'Done', icon: Archive, color: 'bg-neutral-400', order: 6 },
};

const STAGE_GROUPS = [
    { id: 'CLONE_IN', label: 'Clones', icon: Sprout, accent: 'accent' as const },
    { id: 'VEGETATIVE', label: 'Vegetative', icon: Leaf, accent: 'success' as const },
    { id: 'FLOWERING', label: 'Flowering', icon: Flower, accent: 'accent' as const },
    { id: 'DRYING', label: 'Drying', icon: Archive, accent: 'warning' as const },
    { id: 'CURING', label: 'Curing', icon: Archive, accent: 'warning' as const },
    { id: 'FINISHED', label: 'Finished', icon: Archive, accent: 'default' as const },
];

// Stage Progress Mini Component
function StageProgressMini({ currentStage }: { currentStage: string }) {
    const stages = ['CLONE_IN', 'VEGETATIVE', 'FLOWERING', 'HARVEST', 'DRYING', 'CURING'];
    const currentIndex = stages.indexOf(currentStage);

    return (
        <div className="flex gap-0.5">
            {stages.map((stage, i) => (
                <div
                    key={stage}
                    className={`h-1 w-3 rounded-full ${i < currentIndex ? 'bg-success' :
                        i === currentIndex ? 'bg-accent' :
                            'bg-subtle'
                        }`}
                />
            ))}
        </div>
    );
}

// Days Badge
function DaysBadge({ startDate }: { startDate: string }) {
    const days = Math.floor((Date.now() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24));
    return (
        <span className="text-[10px] text-tertiary flex items-center gap-1">
            <Calendar size={10} />
            Day {days}
        </span>
    );
}

// METRC Sync Status Badge
function MetrcBadge({ synced = true }: { synced?: boolean }) {
    if (synced) {
        return (
            <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-medium bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400" title="Synced with METRC">
                <Cloud size={9} />
                METRC
            </span>
        );
    }
    return (
        <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400" title="Not synced with METRC">
            <CloudOff size={9} />
            Pending
        </span>
    );
}

export default function BatchesPage() {
    const { addToast } = useToast();
    const [batches, setBatches] = useState<Batch[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedBatch, setSelectedBatch] = useState<Batch | null>(null);
    const [weightLogBatch, setWeightLogBatch] = useState<Batch | null>(null);
    const [createTaskBatch, setCreateTaskBatch] = useState<Batch | null>(null);
    const [ipmBatch, setIpmBatch] = useState<Batch | null>(null);
    const [scoutingBatch, setScoutingBatch] = useState<Batch | null>(null);

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

    const fetchBatches = async (showToast = false) => {
        setLoading(true);
        try {
            const data = await batchesApi.getAll();
            setBatches(data);
            if (showToast) addToast('Batches refreshed', 'info');
        } catch (e) {
            console.error(e);
            addToast('Failed to load batches', 'error');
        } finally {
            setLoading(false);
        }
    };

    const groupedBatches = STAGE_GROUPS.map(group => ({
        ...group,
        items: batches.filter(b => b.stage === group.id)
    })).filter(group => group.items.length > 0);

    const handlePullRefresh = async () => {
        await fetchBatches(true);
    };

    return (
        <PullToRefresh onRefresh={handlePullRefresh} disabled={loading}>
            <div className="space-y-6 pb-20 animate-in">
                <PageHeader
                    title="Batches"
                    subtitle={loading ? 'Loading...' : `${batches.length} active batches`}
                    actions={
                        <button className="btn btn-primary">
                            <Plus size={16} />
                            <span className="hidden md:inline">New Batch</span>
                        </button>
                    }
                />

                <div className="space-y-6">
                    {loading ? (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                            {Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}
                        </div>
                    ) : groupedBatches.length === 0 ? (
                        <EmptyState
                            icon={Sprout}
                            title="No active batches"
                            description="Get started by creating your first batch."
                            action={
                                <button className="btn btn-primary">
                                    <Plus size={16} />
                                    Start Batch
                                </button>
                            }
                        />
                    ) : (
                        groupedBatches.map(group => (
                            <div key={group.id} className="space-y-3">
                                <SectionHeader
                                    icon={group.icon}
                                    title={group.label}
                                    count={group.items.length}
                                    accent={group.accent}
                                />

                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                    {group.items.map(batch => {
                                        // Extract batch code from name (e.g., "B001" from "[DEMO] Gorilla Glue #4 - B001")
                                        const batchCode = batch.name.match(/B\d{3}/)?.[0] || batch.id.slice(0, 6).toUpperCase();

                                        return (
                                            <div key={batch.id} className="card group overflow-hidden">
                                                {/* Clickable Header */}
                                                <Link
                                                    to={`/batches/${batch.id}`}
                                                    className="block p-4 hover:bg-tertiary transition-colors"
                                                >
                                                    <div className="flex justify-between items-start mb-2">
                                                        <div className="flex-1 min-w-0">
                                                            {/* Batch Code Badge + Strain Name */}
                                                            <div className="flex items-center gap-2 mb-1">
                                                                <span className="text-[10px] font-mono font-medium px-1.5 py-0.5 rounded bg-accent-muted text-accent">
                                                                    {batchCode}
                                                                </span>
                                                                <MetrcBadge synced={true} />
                                                                <h4 className="font-medium text-primary text-sm truncate">
                                                                    {batch.strain}
                                                                </h4>
                                                            </div>
                                                            {/* Plant count + Room */}
                                                            <div className="flex items-center gap-2 text-xs text-tertiary">
                                                                <span>{batch.plantCount} plants</span>
                                                                {batch.room && (
                                                                    <>
                                                                        <span>•</span>
                                                                        <span>{batch.room.name?.replace('[DEMO] ', '')}</span>
                                                                    </>
                                                                )}
                                                            </div>
                                                        </div>
                                                        <ChevronRight size={14} className="text-tertiary flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />
                                                    </div>

                                                    {/* Progress & Days */}
                                                    <div className="flex items-center justify-between mt-3">
                                                        <StageProgressMini currentStage={batch.stage} />
                                                        <DaysBadge startDate={batch.startDate} />
                                                    </div>
                                                </Link>

                                                {/* Quick Actions */}
                                                <div className="px-3 py-2 border-t border-subtle bg-tertiary/30 flex items-center justify-end">
                                                    <div className="flex gap-0.5">
                                                        <ActionButton
                                                            icon={Search}
                                                            label="Scout"
                                                            onClick={() => setScoutingBatch(batch)}
                                                            variant="accent"
                                                        />
                                                        <ActionButton
                                                            icon={Bug}
                                                            label="IPM"
                                                            onClick={() => setIpmBatch(batch)}
                                                            variant="destructive"
                                                        />
                                                        <ActionButton
                                                            icon={MoveRight}
                                                            label="Transition"
                                                            onClick={() => setSelectedBatch(batch)}
                                                            variant="success"
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* Modals */}
                {selectedBatch && (
                    <BatchTransitionModal
                        batch={selectedBatch}
                        onClose={() => setSelectedBatch(null)}
                        onSuccess={() => {
                            fetchBatches();
                            setSelectedBatch(null);
                        }}
                    />
                )}
                {weightLogBatch && (
                    <WeightLogModal
                        batch={weightLogBatch}
                        onClose={() => setWeightLogBatch(null)}
                        onSuccess={() => fetchBatches()}
                    />
                )}
                {createTaskBatch && (
                    <CreateTaskModal
                        isOpen={true}
                        initialBatchId={createTaskBatch.id}
                        onClose={() => setCreateTaskBatch(null)}
                        onSuccess={() => {
                            setCreateTaskBatch(null);
                            addToast('Task created!', 'success');
                        }}
                    />
                )}
                {ipmBatch && (
                    <IPMScheduleModal
                        batch={ipmBatch}
                        onClose={() => setIpmBatch(null)}
                    />
                )}
                {scoutingBatch && (
                    <ScoutingModal
                        batch={scoutingBatch}
                        onClose={() => setScoutingBatch(null)}
                        onSuccess={() => {
                            fetchBatches();
                            addToast('Scouting report logged', 'success');
                        }}
                    />
                )}
            </div>
        </PullToRefresh>
    );
}
