'use client';

import { useState } from 'react';
import { XMarkIcon, ExclamationTriangleIcon } from '@heroicons/react/24/outline';

interface PageHeaderProps {
    title: string;
    subtitle?: string;
    action?: React.ReactNode;
}
export function PageHeader({ title, subtitle, action }: PageHeaderProps) {
    return (
        <div className="bg-white rounded-xl shadow-sm p-6 border-l-4 border-brand flex justify-between items-center">
            <div>
                <h1 className="text-2xl font-bold text-main">{title}</h1>
                {subtitle && <p className="text-sec mt-1 text-sm">{subtitle}</p>}
            </div>
            {action}
        </div>
    );
}

export function EmptyState({ message = 'No data found' }: { message?: string }) {
    return (
        <div className="text-center py-16">
            <div className="w-16 h-16 bg-orange-50 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-8 h-8 text-brand" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                </svg>
            </div>
            <p className="text-sec">{message}</p>
        </div>
    );
}

export function LoadingSpinner() {
    return (
        <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-brand" />
        </div>
    );
}

interface StatusBadgeProps { active: boolean; activeLabel?: string; inactiveLabel?: string }
export function StatusBadge({ active, activeLabel = 'Active', inactiveLabel = 'Inactive' }: StatusBadgeProps) {
    return (
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
            <span className={`w-1.5 h-1.5 rounded-full mr-1.5 ${active ? 'bg-green-500' : 'bg-gray-400'}`} />
            {active ? activeLabel : inactiveLabel}
        </span>
    );
}

interface ActionButtonProps { onClick: () => void; variant: 'edit' | 'delete' | 'view' | 'set-current' | 'set-active'; label?: string }
export function ActionButton({ onClick, variant, label }: ActionButtonProps) {
    const styles = {
        edit: 'text-brand hover:bg-orange-50',
        delete: 'text-red-500 hover:bg-red-50',
        view: 'text-blue-500 hover:bg-blue-50',
        'set-current': 'text-green-600 hover:bg-green-50',
        'set-active': 'text-purple-600 hover:bg-purple-50',
    };
    const icons = {
        edit: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />,
        delete: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />,
        view: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />,
        'set-current': <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />,
        'set-active': <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />,
    };
    return (
        <button onClick={onClick} title={label || variant} className={`p-1.5 rounded-lg transition-colors ${styles[variant]}`}>
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">{icons[variant]}</svg>
        </button>
    );
}

interface ConfirmDialogProps { isOpen: boolean; onClose: () => void; onConfirm: () => void; title: string; message: string; loading?: boolean }
export function ConfirmDialog({ isOpen, onClose, onConfirm, title, message, loading }: ConfirmDialogProps) {
    if (!isOpen) return null;
    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div className="absolute inset-0 bg-black/50" onClick={onClose} />
            <div className="relative bg-white rounded-2xl shadow-2xl max-w-sm w-full p-6">
                <div className="flex items-center gap-3 mb-4">
                    <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0">
                        <ExclamationTriangleIcon className="w-5 h-5 text-red-600" />
                    </div>
                    <h3 className="font-semibold text-main text-lg">{title}</h3>
                </div>
                <p className="text-sec text-sm mb-6">{message}</p>
                <div className="flex gap-3">
                    <button onClick={onClose} className="flex-1 px-4 py-2 border border-gray-200 rounded-lg text-sec hover:bg-gray-50 text-sm font-medium transition-colors">Cancel</button>
                    <button onClick={onConfirm} disabled={loading} className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm font-medium transition-colors disabled:opacity-50">
                        {loading ? 'Deleting...' : 'Delete'}
                    </button>
                </div>
            </div>
        </div>
    );
}

interface ModalProps { isOpen: boolean; onClose: () => void; title: string; children: React.ReactNode; size?: 'sm' | 'md' | 'lg' }
export function Modal({ isOpen, onClose, title, children, size = 'md' }: ModalProps) {
    if (!isOpen) return null;
    const widths = { sm: 'max-w-sm', md: 'max-w-lg', lg: 'max-w-2xl' };
    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 overflow-y-auto">
            <div className="absolute inset-0 bg-black/50" onClick={onClose} />
            <div className={`relative bg-white rounded-2xl shadow-2xl w-full ${widths[size]} my-4`}>
                <div className="flex items-center justify-between p-6 border-b border-gray-100">
                    <h3 className="font-semibold text-main text-lg">{title}</h3>
                    <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-400 transition-colors">
                        <XMarkIcon className="w-5 h-5" />
                    </button>
                </div>
                <div className="p-6">{children}</div>
            </div>
        </div>
    );
}

interface FormFieldProps { label: string; required?: boolean; error?: string; children: React.ReactNode; hint?: string }
export function FormField({ label, required, error, children, hint }: FormFieldProps) {
    return (
        <div>
            <label className="block text-sm font-medium text-main mb-1.5">
                {label} {required && <span className="text-red-500">*</span>}
            </label>
            {children}
            {hint && <p className="text-xs text-sec mt-1">{hint}</p>}
            {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
        </div>
    );
}

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { error?: boolean }
export function Input({ error, className, ...props }: InputProps) {
    return (
        <input
            {...props}
            className={`w-full px-3 py-2.5 border rounded-lg text-sm text-main placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand focus:border-transparent transition-all ${error ? 'border-red-300 bg-red-50' : 'border-gray-200'} ${className || ''}`}
        />
    );
}

interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { error?: boolean }
export function Textarea({ error, className, ...props }: TextareaProps) {
    return (
        <textarea
            {...props}
            className={`w-full px-3 py-2.5 border rounded-lg text-sm text-main placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-brand focus:border-transparent transition-all resize-none ${error ? 'border-red-300 bg-red-50' : 'border-gray-200'} ${className || ''}`}
        />
    );
}

interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> { error?: boolean }
export function Select({ error, className, children, ...props }: SelectProps) {
    return (
        <select
            {...props}
            className={`w-full px-3 py-2.5 border rounded-lg text-sm text-main focus:outline-none focus:ring-2 focus:ring-brand focus:border-transparent transition-all ${error ? 'border-red-300 bg-red-50' : 'border-gray-200'} ${className || ''}`}
        >
            {children}
        </select>
    );
}

interface ToggleProps { checked: boolean; onChange: (val: boolean) => void; label?: string }
export function Toggle({ checked, onChange, label }: ToggleProps) {
    return (
        <label className="flex items-center gap-2 cursor-pointer">
            <div
                onClick={() => onChange(!checked)}
                className={`relative w-10 h-5 rounded-full transition-colors ${checked ? 'bg-brand' : 'bg-gray-300'}`}
            >
                <span className={`absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all ${checked ? 'left-5.5 translate-x-1' : 'left-0.5'}`} style={{ left: checked ? '22px' : '2px' }} />
            </div>
            {label && <span className="text-sm text-sec">{label}</span>}
        </label>
    );
}

interface ImageUploadProps { currentImage?: string; onChange: (file: File | null) => void; label?: string }
export function ImageUpload({ currentImage, onChange, label = 'Image' }: ImageUploadProps) {
    const [preview, setPreview] = useState<string | null>(null);
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => setPreview(reader.result as string);
            reader.readAsDataURL(file);
        } else {
            setPreview(null);
        }
        onChange(file);
    };

    const displaySrc = preview || (currentImage ? `${apiUrl}/storage/${currentImage}` : null);

    return (
        <div>
            <label className="block text-sm font-medium text-main mb-1.5">{label}</label>
            {displaySrc && (
                <div className="mb-2 relative w-32 h-32 rounded-lg overflow-hidden border border-gray-200">
                    <img src={displaySrc} alt="preview" className="w-full h-full object-cover" />
                    <button type="button" onClick={() => { setPreview(null); onChange(null); }} className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-0.5">
                        <XMarkIcon className="w-3 h-3" />
                    </button>
                </div>
            )}
            <input type="file" accept="image/*" onChange={handleChange} className="block w-full text-sm text-sec file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-orange-50 file:text-brand hover:file:bg-orange-100" />
        </div>
    );
}

interface TableProps { headers: string[]; children: React.ReactNode }
export function Table({ headers, children }: TableProps) {
    return (
        <div className="bg-white rounded-xl shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-100">
                    <thead>
                        <tr className="bg-gray-50">
                            {headers.map((h, i) => (
                                <th key={i} className="px-6 py-3.5 text-left text-xs font-semibold text-sec uppercase tracking-wider">{h}</th>
                            ))}
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-50">{children}</tbody>
                </table>
            </div>
        </div>
    );
}

export function TableRow({ children }: { children: React.ReactNode }) {
    return <tr className="hover:bg-orange-50/30 transition-colors">{children}</tr>;
}

export function TableCell({ children, className }: { children: React.ReactNode; className?: string }) {
    return <td className={`px-6 py-4 text-sm text-main whitespace-nowrap ${className || ''}`}>{children}</td>;
}

interface SubmitButtonProps { loading: boolean; label?: string; loadingLabel?: string }
export function SubmitButton({ loading, label = 'Save', loadingLabel = 'Saving...' }: SubmitButtonProps) {
    return (
        <button type="submit" disabled={loading} className="w-full py-2.5 px-4 bg-brand text-white rounded-lg font-medium text-sm hover:bg-orange-600 disabled:opacity-50 transition-all">
            {loading ? loadingLabel : label}
        </button>
    );
}

export function AddButton({ onClick, label = 'Add New' }: { onClick: () => void; label?: string }) {
    return (
        <button onClick={onClick} className="flex items-center gap-2 px-4 py-2 bg-brand text-white rounded-lg text-sm font-medium hover:bg-orange-600 transition-all">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            {label}
        </button>
    );
}

export function ErrorAlert({ message }: { message: string }) {
    if (!message) return null;
    return (
        <div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg text-sm">{message}</div>
    );
}

export function ImagePreview({ src, alt, size = 10 }: { src?: string; alt: string; size?: number }) {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
    if (!src) return <div className={`w-${size} h-${size} bg-gray-100 rounded-lg flex items-center justify-center`}><span className="text-gray-400 text-xs">No image</span></div>;
    return <img src={`${apiUrl}/storage/${src}`} alt={alt} className={`w-${size} h-${size} object-cover rounded-lg`} />;
}