import type { FC } from 'react';
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMagnifyingGlass } from '@fortawesome/pro-duotone-svg-icons';

const SearchLg: FC<{ className?: string }> = ({ className }) => <FontAwesomeIcon icon={faMagnifyingGlass} className={className} />;
import { Input } from '@/components/base/input/input';
import { Badge } from '@/components/base/badges/badges';
import { Tabs, TabList, Tab, TabPanel } from '@/components/application/tabs/tabs';
import { cx } from '@/utils/cx';
import type { WhatsAppTemplate } from '@/types/entities';

interface TemplateListProps {
    templates: WhatsAppTemplate[];
    selectedId: string | null;
    onSelect: (id: string) => void;
}

type TabId = 'all' | 'campaign' | 'custom';

export const TemplateList = ({ templates, selectedId, onSelect }: TemplateListProps) => {
    const [search, setSearch] = useState('');
    const [activeTab, setActiveTab] = useState<TabId>('all');

    const filtered = templates.filter((t) => {
        const matchesSearch =
            !search ||
            t.name?.toLowerCase().includes(search.toLowerCase()) ||
            t.body?.toLowerCase().includes(search.toLowerCase());

        const matchesTab =
            activeTab === 'all' ||
            (activeTab === 'campaign' && t.linkedCampaignId !== null) ||
            (activeTab === 'custom' && t.linkedCampaignId === null);

        return matchesSearch && matchesTab;
    });

    const tabs = [
        { id: 'all' as TabId, label: `All (${templates.length})` },
        { id: 'campaign' as TabId, label: 'By Campaign' },
        { id: 'custom' as TabId, label: 'Custom' },
    ];

    return (
        <div className="w-96 border-r border-secondary bg-primary flex flex-col h-full flex-shrink-0">
            {/* Header */}
            <div className="p-5 border-b border-secondary space-y-3">
                <p className="text-sm font-bold text-primary">Message Templates</p>
                <Input
                    size="sm"
                    placeholder="Search templates..."
                    icon={SearchLg}
                    value={search}
                    onChange={(val) => setSearch(val)}
                    aria-label="Search templates"
                />
            </div>

            {/* Tabs */}
            <div className="border-b border-secondary px-5">
                <Tabs selectedKey={activeTab} onSelectionChange={(key) => setActiveTab(key as TabId)}>
                    <TabList type="underline" size="sm" items={tabs}>
                        {(item) => <Tab key={item.id} id={item.id} label={item.label} />}
                    </TabList>
                    {tabs.map((tab) => (
                        <TabPanel key={tab.id} id={tab.id} />
                    ))}
                </Tabs>
            </div>

            {/* Scrollable list */}
            <div className="flex-1 overflow-y-auto p-2">
                {filtered.length === 0 && (
                    <p className="py-8 text-center text-xs text-tertiary">No templates found.</p>
                )}
                {filtered.map((template) => {
                    const isSelected = template.id === selectedId;
                    const isPending = template.approvalStatus === 'PENDING';
                    const deliveredRate =
                        template.sendCount && template.sendCount > 0
                            ? Math.round(((template.deliveredCount ?? 0) / template.sendCount) * 100)
                            : 0;

                    return (
                        <button
                            key={template.id}
                            type="button"
                            onClick={() => onSelect(template.id)}
                            className={cx(
                                'w-full text-left p-3.5 rounded-xl border-2 transition duration-100 ease-linear cursor-pointer',
                                isSelected
                                    ? 'bg-brand-primary border-brand'
                                    : 'border-transparent hover:bg-secondary',
                                isPending && 'opacity-60',
                            )}
                        >
                            {/* Top row */}
                            <div className="flex items-center justify-between gap-2 mb-1">
                                <span className={cx('text-sm font-semibold truncate', isSelected ? 'text-white' : 'text-primary')}>
                                    {template.name}
                                </span>
                                {template.linkedCampaignId ? (
                                    <Badge type="pill-color" color="brand" size="sm">
                                        Campaign
                                    </Badge>
                                ) : (
                                    <Badge type="pill-color" color="gray" size="sm">
                                        Custom
                                    </Badge>
                                )}
                            </div>

                            {/* Preview text */}
                            <p className={cx('text-xs line-clamp-2 mb-1.5', isSelected ? 'text-white/80' : 'text-tertiary')}>
                                {template.body}
                            </p>

                            {/* Meta row */}
                            <div className={cx('flex gap-3 text-xs', isSelected ? 'text-white/70' : 'text-quaternary')}>
                                {template.approvalStatus === 'APPROVED' ? (
                                    <span className={isSelected ? 'text-white/90' : 'text-success-primary'}>✓ Approved</span>
                                ) : (
                                    <span className={isSelected ? 'text-white/90' : 'text-warning-primary'}>⏳ Pending</span>
                                )}
                                <span>
                                    Sent <strong>{template.sendCount ?? 0}</strong> times
                                </span>
                                <span>
                                    <strong>{deliveredRate}%</strong> delivered
                                </span>
                            </div>
                        </button>
                    );
                })}
            </div>
        </div>
    );
};
