import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, useForm, usePage } from "@inertiajs/react";
import { Card, CardContent } from "@/components/ui/card";
import SearchInput from "@/Components/SearchInput";
import useTranslation from "@/Hooks/useTranslation";
import { Clock, PlayCircle, Briefcase, User as UserIcon, MapPin, Edit2, X, Search } from "lucide-react";
import { useState } from "react";
import { router } from "@inertiajs/react";
import Modal from "@/Components/Modal";
import { usePermissions } from "@/lib/usePermissions";
import { Button } from "@/components/ui/button";
import SecondaryButton from "@/Components/SecondaryButton";

import ContactSelectorModal from "@/Pages/Business/Contacts/Partials/ContactSelectorModal";
import ActivityHistoryModal from "@/Pages/Execution/Tasks/Partials/ActivityHistoryModal";
import { Building2, History } from "lucide-react";

function EditWorkLogModal({ show, onClose, workLog, contacts, affaires }) {
    const { t } = useTranslation();
    const [isContactSelectorOpen, setIsContactSelectorOpen] = useState(false);

    const { data, setData, put, processing, errors } = useForm({
        notes: workLog?.notes || "",
        business_contact_id: workLog?.business_contact_id || "",
        business_tier_id: workLog?.business_tier_id || "",
        affaire_id: workLog?.affaire_id || "",
        task_id: workLog?.task_id || "",
        started_at: workLog?.started_at || "",
        ended_at: workLog?.ended_at || "",
    });

    const submit = (e) => {
        e.preventDefault();
        put(route('tasks.logs.update', { task: workLog.task_id, workLog: workLog.id }), {
            preserveScroll: true,
            onSuccess: () => onClose(),
        });
    };

    return (
        <Modal show={show} onClose={onClose} maxWidth="lg">
            <div className="p-6">
                <div className="flex justify-between items-center mb-6">
                    <h2 className="text-xl font-bold text-slate-900 dark:text-white">
                        Edit Work Log
                    </h2>
                    <button onClick={onClose} className="text-slate-400 hover:text-slate-500">
                        <X className="size-5" />
                    </button>
                </div>

                <form onSubmit={submit} className="space-y-4">
                    <div>
                        <label className="block text-sm font-bold text-slate-700 dark:text-slate-300 mb-1">
                            Notes / Comments
                        </label>
                        <textarea
                            value={data.notes}
                            onChange={e => setData('notes', e.target.value)}
                            className="w-full rounded-md border-slate-300 dark:border-slate-700 dark:bg-slate-900 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                            rows="4"
                            placeholder="Add notes about this work session..."
                        />
                        {errors.notes && <div className="text-red-500 text-xs mt-1">{errors.notes}</div>}
                    </div>

                    <div>
                        <label className="block text-sm font-bold text-slate-700 dark:text-slate-300 mb-1">
                            Affaire Workspace
                        </label>
                        <select
                            value={data.affaire_id}
                            onChange={e => {
                                setData('affaire_id', e.target.value);
                                if (e.target.value) {
                                    setData('business_contact_id', '');
                                    setData('business_tier_id', '');
                                }
                            }}
                            className="w-full rounded-md border-slate-300 dark:border-slate-700 dark:bg-slate-900 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        >
                            <option value="">-- No Affaire --</option>
                            {affaires.map(a => (
                                <option key={a.id} value={a.id}>
                                    {a.reference_number ? `[${a.reference_number}] ` : ''}{a.title}
                                </option>
                            ))}
                        </select>
                        {errors.affaire_id && <div className="text-red-500 text-xs mt-1">{errors.affaire_id}</div>}
                    </div>

                    {!data.affaire_id && (
                        <div>
                            <label className="block text-sm font-bold text-slate-700 dark:text-slate-300 mb-1">
                                Business Contact / Tier
                            </label>
                            
                            {(data.business_contact_id || data.business_tier_id) ? (
                                <div className="flex items-center justify-between p-3 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50">
                                    <div className="flex items-center gap-3">
                                        {contacts.find(c => (data.business_tier_id && c.is_tier && String(c.id) === String(data.business_tier_id)) || (data.business_contact_id && !c.is_tier && String(c.id) === String(data.business_contact_id)))?.type === "contact" ? <UserIcon className="size-4" /> : <Building2 className="size-4" />}
                                        <div className="text-sm font-bold text-slate-700 dark:text-slate-200">
                                            {(() => {
                                                const sc = contacts.find(c => (data.business_tier_id && c.is_tier && String(c.id) === String(data.business_tier_id)) || (data.business_contact_id && !c.is_tier && String(c.id) === String(data.business_contact_id)));
                                                if (sc) {
                                                    if (sc.is_tier) return sc.name || "Unknown Tier";
                                                    const civility = sc.civility ? sc.civility + " " : "";
                                                    const first = sc.firstname || "";
                                                    const last = sc.lastname || "";
                                                    const fullName = `${civility}${first} ${last}`.trim();
                                                    return fullName || "Unnamed Contact";
                                                }
                                                return "Selected Contact";
                                            })()}
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <button
                                            type="button"
                                            onClick={() => setIsContactSelectorOpen(true)}
                                            className="text-xs font-bold text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
                                        >
                                            Change
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setData('business_contact_id', '');
                                                setData('business_tier_id', '');
                                            }}
                                            className="text-slate-400 hover:text-red-500"
                                        >
                                            <X className="size-4" />
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <button
                                    type="button"
                                    onClick={() => setIsContactSelectorOpen(true)}
                                    className="w-full flex items-center justify-center gap-2 p-3 rounded-lg border border-dashed border-slate-300 dark:border-slate-600 hover:bg-slate-50 dark:hover:bg-slate-800/50 text-slate-500 transition-colors"
                                >
                                    <UserIcon className="size-4" />
                                    <span className="text-sm font-bold">Select Contact</span>
                                </button>
                            )}

                            {(errors.business_contact_id || errors.business_tier_id) && (
                                <div className="text-red-500 text-xs mt-1">
                                    {errors.business_contact_id || errors.business_tier_id}
                                </div>
                            )}

                            {/* Contact Selector Modal embedded inside */}
                            <ContactSelectorModal
                                show={isContactSelectorOpen}
                                onClose={() => setIsContactSelectorOpen(false)}
                                contacts={contacts}
                                allowTiers={true}
                                selectedContactId={data.business_contact_id || data.business_tier_id}
                                onSelect={(contact) => {
                                    const isTier = contact.is_tier !== undefined ? contact.is_tier : (contact.type !== "contact");
                                    setData(d => ({
                                        ...d,
                                        business_tier_id: isTier ? contact.id : "",
                                        business_contact_id: !isTier ? contact.id : "",
                                        affaire_id: "", // clear affaire since contact is set
                                    }));
                                    setIsContactSelectorOpen(false);
                                }}
                            />
                        </div>
                    )}

                    <div className="flex justify-end gap-3 mt-6">
                        <SecondaryButton type="button" onClick={onClose}>
                            Cancel
                        </SecondaryButton>
                        <Button type="submit" disabled={processing} className="bg-blue-600 hover:bg-blue-700 text-white">
                            Save Changes
                        </Button>
                    </div>
                </form>
            </div>
        </Modal>
    );
}

export default function WorkLogsIndex({ filters, workLogs, contacts, affaires }) {
    const { t } = useTranslation();
    const { auth } = usePage().props;
    const authUser = auth.user;
    const { can } = usePermissions();
    const canEditActivity = can("edit_activity");

    const [editingLog, setEditingLog] = useState(null);
    const [viewingHistoryLog, setViewingHistoryLog] = useState(null);
    const [minDuration, setMinDuration] = useState(filters.min_duration ?? '');

    return (
        <AuthenticatedLayout>
            <Head title={t('sidebar.work_logs')} />

            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                    <div>
                        <h1 className="text-2xl font-black text-slate-900 dark:text-white tracking-tight">
                            {t('sidebar.work_logs')}
                        </h1>
                    </div>
                    <div className="flex items-center gap-3">
                        <div className="flex items-center gap-2">
                            <label className="text-xs font-bold text-slate-500 uppercase tracking-widest whitespace-nowrap">
                                {t('execution.work_logs.min_duration', 'Durée min (h)')}
                            </label>
                            <div className="relative">
                                <input
                                    type="number"
                                    min="0"
                                    value={minDuration}
                                    onChange={(e) => {
                                        setMinDuration(e.target.value);
                                        const type = new URLSearchParams(window.location.search).get('type');
                                        const params = { search: filters.search, min_duration: e.target.value };
                                        if (type) params.type = type;
                                        router.get(route('work-logs.index'), params, { preserveState: true, replace: true });
                                    }}
                                    placeholder="Ex: 8"
                                    className="w-24 pl-3 pr-8 py-2 text-sm rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all shadow-sm"
                                />
                                {minDuration && (
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setMinDuration('');
                                            const type = new URLSearchParams(window.location.search).get('type');
                                            const params = { search: filters.search, min_duration: '' };
                                            if (type) params.type = type;
                                            router.get(route('work-logs.index'), params, { preserveState: true, replace: true });
                                        }}
                                        className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                                    >
                                        <X className="size-3.5" />
                                    </button>
                                )}
                            </div>
                        </div>
                        <SearchInput
                            routeName="work-logs.index"
                            filters={filters}
                            extraParams={{ 
                                min_duration: minDuration,
                                ...(new URLSearchParams(window.location.search).get('type') ? { type: new URLSearchParams(window.location.search).get('type') } : {}) 
                            }}
                            placeholder={t('sidebar.search')}
                        />
                    </div>
                </div>

                <Card className="border-none shadow-sm bg-white dark:bg-slate-900">
                    <CardContent className="space-y-4 pt-6">
                        {workLogs.data.length === 0 && (
                            <p className="text-sm font-bold text-slate-500 py-4 text-center">
                                {t('dashboard.no_recent_logs')}
                            </p>
                        )}
                        {workLogs.data.map((log) => {
                            const canEdit = log.user_id === authUser.id || canEditActivity;
                            return (
                                <div
                                    key={log.id}
                                    className="flex items-start justify-between p-4 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors group border border-transparent hover:border-slate-200 dark:hover:border-slate-700"
                                >
                                    <div className="flex items-start gap-4 w-full">
                                        <div className="size-10 rounded-lg bg-slate-100 dark:bg-slate-800 flex items-center justify-center shrink-0 mt-1">
                                            {log.is_active ? (
                                                <Clock className="size-5 text-emerald-500 animate-pulse" />
                                            ) : (
                                                <PlayCircle className="size-5 text-slate-400" />
                                            )}
                                        </div>
                                        <div className="flex-1 min-w-0 space-y-1.5">
                                            <div className="flex justify-between items-start">
                                                <Link
                                                    href={route("tasks.show", {
                                                        task: log.task_id,
                                                        ...(log.affaire_id && { affaire_id: log.affaire_id }),
                                                        ...(log.business_contact_id && { business_contact_id: log.business_contact_id }),
                                                    })}
                                                >
                                                    <p className="text-base font-bold truncate max-w-[500px] hover:text-blue-600 transition-colors dark:text-slate-200">
                                                        {log.task_title}
                                                    </p>
                                                </Link>
                                                
                                                <div className="flex items-center gap-2 shrink-0">
                                                    {log.duration && (
                                                        <span className="text-sm font-black text-slate-700 dark:text-slate-200 bg-slate-100 dark:bg-slate-800 px-3 py-1 rounded-full">
                                                            {log.duration}
                                                        </span>
                                                    )}
                                                    {log.histories?.length > 0 && (
                                                        <button 
                                                            onClick={() => setViewingHistoryLog(log)}
                                                            className="p-1.5 rounded-md text-slate-400 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-all opacity-0 group-hover:opacity-100 focus:opacity-100"
                                                            title="View History"
                                                        >
                                                            <History className="size-4" />
                                                        </button>
                                                    )}
                                                    {canEdit && (
                                                        <button 
                                                            onClick={() => setEditingLog(log)}
                                                            className="p-1.5 rounded-md text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-all opacity-0 group-hover:opacity-100 focus:opacity-100"
                                                            title="Edit Work Log"
                                                        >
                                                            <Edit2 className="size-4" />
                                                        </button>
                                                    )}
                                                </div>
                                            </div>
                                            
                                            <div className="text-xs text-slate-500 flex flex-wrap items-center gap-x-3 gap-y-2">
                                                <span className="font-medium text-slate-700 dark:text-slate-300">
                                                    {log.user_name}
                                                </span>
                                                <span className="text-slate-400">|</span>
                                                <span>
                                                    {log.started_at_formatted}
                                                    {log.ended_at_formatted ? ` - ${log.ended_at_formatted}` : ''}
                                                </span>
                                                
                                                {(log.business_contact_name || log.affaire_title) && (
                                                    <span className="text-slate-400">|</span>
                                                )}

                                                {log.business_contact_name && (
                                                    <span className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-indigo-600 dark:text-indigo-400 bg-indigo-500/10 px-1.5 py-0.5 rounded">
                                                        {log.business_contact_type === 'tier' ? <Building2 className="size-3" /> : <UserIcon className="size-3" />}
                                                        {log.business_contact_civility ? `${log.business_contact_civility} ` : ''}{log.business_contact_name}
                                                    </span>
                                                )}
                                                {log.affaire_title && (
                                                    <span className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-blue-600 dark:text-blue-400 bg-blue-500/10 px-1.5 py-0.5 rounded">
                                                        <Briefcase className="size-3" />
                                                        {log.affaire_reference || log.affaire_title}
                                                    </span>
                                                )}
                                            </div>

                                            {log.notes && (
                                                <div className="w-full mt-2 p-3 rounded-lg bg-slate-50 dark:bg-slate-800/80 text-[12px] text-slate-600 dark:text-slate-300 italic border border-slate-100 dark:border-slate-700/50 relative">
                                                    <div className="absolute left-0 top-0 bottom-0 w-1 bg-slate-300 dark:bg-slate-600 rounded-l-lg"></div>
                                                    <div className="pl-2">{log.notes}</div>
                                                </div>
                                            )}

                                            <div className="flex gap-4 pt-1">
                                                {log.start_lat && log.start_lng && (
                                                    <a
                                                        href={`https://www.google.com/maps?q=${log.start_lat},${log.start_lng}`}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="text-amber-600 hover:text-amber-800 flex items-center gap-1 text-[10px] font-black uppercase"
                                                    >
                                                        <MapPin className="size-3 flex-shrink-0" />
                                                        <span>{t('dashboard.start')}</span>
                                                    </a>
                                                )}
                                                {log.lat && log.lng && (
                                                    <a
                                                        href={`https://www.google.com/maps?q=${log.lat},${log.lng}`}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="text-blue-600 hover:text-blue-800 flex items-center gap-1 text-[10px] font-black uppercase"
                                                    >
                                                        <MapPin className="size-3 flex-shrink-0" />
                                                        <span>{t('dashboard.end')}</span>
                                                    </a>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                        
                        {/* Pagination */}
                        {workLogs.links && workLogs.links.length > 3 && (
                            <div className="flex flex-wrap items-center justify-center gap-1 pt-6 pb-2 border-t border-slate-100 dark:border-slate-800">
                                {workLogs.links.map((link, k) => 
                                    !link.url ? (
                                        <span
                                            key={k}
                                            className="px-3 py-1.5 text-xs font-bold rounded-lg bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 opacity-50 cursor-not-allowed"
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    ) : (
                                        <Link
                                            key={k}
                                            href={link.url}
                                            className={`px-3 py-1.5 text-xs font-bold rounded-lg transition-colors ${
                                                link.active
                                                    ? "bg-blue-600 text-white shadow-md"
                                                    : "bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700"
                                            }`}
                                            dangerouslySetInnerHTML={{ __html: link.label }}
                                        />
                                    )
                                )}
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Edit Modal */}
            {editingLog && (
                <EditWorkLogModal
                    show={!!editingLog}
                    onClose={() => setEditingLog(null)}
                    workLog={editingLog}
                    contacts={contacts}
                    affaires={affaires}
                />
            )}

            <ActivityHistoryModal
                show={!!viewingHistoryLog}
                onClose={() => setViewingHistoryLog(null)}
                log={viewingHistoryLog}
                affaires={affaires}
            />
        </AuthenticatedLayout>
    );
}
