"use client";

import React, { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { FollowUpChecklist, useUpdateFollowUpChecklist } from "@/hooks/useFollowUpChecklist";
import { Loader2, Save, User, Pencil } from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

import { format } from "date-fns";

interface FollowUpChecklistModalProps {
    isOpen: boolean;
    onClose: () => void;
    data: FollowUpChecklist[] | null | undefined;
    phone: string;
    contactName?: string;
    categories?: any[];
    isLoading: boolean;
}

export default function FollowUpChecklistModal({
    isOpen,
    onClose,
    data,
    categories,
    phone,
    contactName,
    isLoading,
}: FollowUpChecklistModalProps) {
    const { mutate: updateFollowUp, isPending } = useUpdateFollowUpChecklist();
    const [editingId, setEditingId] = useState<number | null>(null);
    const [statusDraft, setStatusDraft] = useState<string>("0");
    const [keteranganDraft, setKeteranganDraft] = useState<string>("");

    const handleEdit = (item: FollowUpChecklist) => {
        setEditingId(item.id);
        setStatusDraft(item.status ? item.status.toString() : "0");
        setKeteranganDraft(item.description || "");
    };

    const handleSave = (id: number) => {
        updateFollowUp(
            {
                id,
                status: parseInt(statusDraft),
                keterangan: keteranganDraft,
                phone,
            },
            {
                onSuccess: () => {
                    setEditingId(null);
                },
            }
        );
    };

    const totalFollowUp = data?.length || 0;
    const doneAndSkipCount = data?.filter(item => item.status === 1 || item.status === 2).length || 0;
    const percentage = totalFollowUp > 0 ? Math.round((doneAndSkipCount / totalFollowUp) * 100) : 0;
    const totalScore = data?.filter(item => item.status === 1).reduce((acc, item) => acc + (item.follow_up?.score || 0), 0) || 0;
    const rating = totalScore >= 100 ? 5 : totalScore >= 80 ? 4 : totalScore >= 60 ? 3 : totalScore >= 25 ? 2 : 1;

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-4xl max-h-[80vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <span>Follow Up Checklist</span>
                            {categories && categories.length > 0 && (
                                <div className="flex gap-1 flex-wrap justify-end">
                                    {categories.map((cat: any) => (
                                        <span key={cat.code}>
                                            - {cat.value}
                                        </span>
                                    ))}
                                </div>
                            )}
                            {totalFollowUp > 0 && (
                                <div className="flex gap-2 ml-2">
                                    <span className={`px-2 py-0.5 rounded-full font-semibold text-[18px] ${
                                        percentage === 100 
                                            ? 'bg-green-100 text-green-700' 
                                            : percentage > 0 
                                                ? 'bg-yellow-100 text-yellow-700' 
                                                : 'bg-blue-100 text-blue-700'
                                    }`}>
                                        {percentage}%
                                    </span>
                                    <span className="px-2 py-0.5 rounded-full font-semibold text-[18px] text-white shadow-sm"
                                        style={{
                                            backgroundColor: 
                                                rating === 5 ? '#7ed957' : 
                                                rating === 4 ? '#0cc0df' : 
                                                rating === 3 ? '#ffde59' : 
                                                rating === 2 ? '#ff914d' : '#b4b4b4',
                                            color: rating === 3 ? '#666' : '#fff'
                                        }}>
                                        {
                                            rating === 5 ? 'Excellent' : 
                                            rating === 4 ? 'Very Good' : 
                                            rating === 3 ? 'Good' : 
                                            rating === 2 ? 'Average' : 'Poor'
                                        }
                                    </span>
                                </div>
                            )}
                            
                        </div>
                        {contactName && (
                            <div className="flex flex-col items-end gap-1 mr-5">
                                <div className="flex items-center gap-2 text-sm font-normal text-gray-600">
                                    <span>{contactName}</span>
                                    <a href={`${process.env.NEXT_PUBLIC_LOGIN_URL?.replace('/login', '') || ''}/admin/prospek/customer?search=${phone}`} target="_blank" rel="noreferrer" className="text-gray-400 hover:text-blue-600 transition-colors">
                                        <User className="h-4 w-4" />
                                    </a>
                                </div>
                                
                            </div>
                        )}
                    </DialogTitle>
                </DialogHeader>

                {isLoading ? (
                    <div className="flex items-center justify-center py-10">
                        <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
                    </div>
                ) : !data || data.length === 0 ? (
                    <div className="text-center py-10 text-gray-500">
                        Tidak ada data Follow Up Checklist untuk kontak ini.
                    </div>
                ) : (
                    <div className="overflow-x-auto mt-4">
                        <table className="w-full text-sm text-left">
                            <thead className="text-xs text-gray-700 bg-gray-100 dark:bg-gray-800 dark:text-gray-300">
                                <tr>
                                    <th className="px-3 py-2">Follow Up</th>
                                    <th className="px-3 py-2 w-[150px]">Status</th>
                                    <th className="px-3 py-2 w-[150px]">Keterangan</th>
                                    <th className="px-3 py-2">Waktu</th>
                                    <th className="px-3 py-2 text-center w-[80px]"></th>
                                </tr>
                            </thead>
                            <tbody>
                                {data.map((item) => (
                                    <tr key={item.id} className="border-b dark:border-gray-700">
                                        <td 
                                            className="px-3 py-1 font-normal" 
                                            style={{ backgroundColor: item.status === 1 ? '#E7F9E0' : item.status === 2 ? '#EEEFF1' : undefined }}
                                        >
                                            <div className="flex flex-col gap-1 items-start">
                                                <div className="flex items-center gap-1 ">
                                                    {item.follow_up.description ? (
                                                        <TooltipProvider delayDuration={100}>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <span className="cursor-help border-gray-400">{item.name}</span>
                                                                </TooltipTrigger>
                                                                <TooltipContent className="max-w-xs">
                                                                    <p className="text-xs">{item.follow_up.description}</p>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>
                                                    ) : (
                                                        <span>{item.name}</span>
                                                    )}
                                                    {item.is_required && (
                                                        <span className="text-red-500 text-xs ml-1">(Wajib)</span>
                                                    )}
                                                </div>
                                                <span style={{backgroundColor:item.follow_up.type_follow_up.color, color:item.follow_up.type_follow_up.text_color}} className="px-1 py rounded text-[10px] font-medium inline-block">
                                                    {item.follow_up.type_follow_up.name}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-3 py-1 w-[150px]">
                                            {editingId === item.id ? (
                                                <select
                                                    value={statusDraft}
                                                    onChange={(e) => setStatusDraft(e.target.value)}
                                                    className="w-full h-8 rounded-md border border-gray-300 bg-white px-2 py-1 text-xs shadow-sm focus:outline-none focus:ring-1 focus:ring-gray-400 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 dark:focus:ring-gray-600"
                                                >
                                                    <option value="" disabled>Status</option>
                                                    <option value="0">___</option>
                                                    <option value="1">Done</option>
                                                    <option value="2">Skip</option>
                                                </select>
                                            ) : (
                                                <span style={{backgroundColor:item.status_follow_up.color, color:item.status_follow_up.text_color}} className="px-1.5 py-0.5 rounded text-xs font-medium">
                                                    {item.status_follow_up.name}
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-3 py-1 w-[150px]">
                                            {editingId === item.id ? (
                                                <Input
                                                    value={keteranganDraft}
                                                    onChange={(e) => setKeteranganDraft(e.target.value)}
                                                    placeholder="Keterangan..."
                                                    className="w-full text-xs h-8 px-2"
                                                />
                                            ) : (
                                                <div className="flex items-center gap-1">
                                                    {(item.status === 0 || item.status === null) && !item.description && (
                                                        <Loader2 className="w-4 h-4 animate-spin text-gray-400 flex-shrink-0" />
                                                    )}
                                                    <span className="text-gray-600 dark:text-gray-400 text-[11px] italic whitespace-normal break-words max-w-[200px]">
                                                        {item.description || ""}
                                                    </span>
                                                </div>
                                            )}
                                        </td>
                                        <td className="px-3 py-1 text-[11px] text-gray-500 whitespace-nowrap flex flex-col gap-1">
                                            <div className="flex flex-row gap-1 items-center">
                                                <TooltipProvider delayDuration={100}>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <span style={{backgroundColor:item.created_by.color, color: item.created_by.color_text || '#fff', fontSize:'9px',textAlign:'center'}} className="w-5 h-4 rounded-sm cursor-help flex items-center justify-center">{item.created_by.initial}</span>
                                                        </TooltipTrigger>
                                                        <TooltipContent>
                                                            <p className="text-xs">Dibuat oleh: {item.created_by.name}</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>
                                                <span className="block">{item.created ? format(new Date(item.created), "dd MMM yyyy HH:mm") : "-"}</span>
                                            </div>
                                            <div className="flex flex-row gap-1 items-center mt-1">
                                                <TooltipProvider delayDuration={100}>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <span style={{backgroundColor:item.updated_by.color, color:item.updated_by.color_text || '#fff', fontSize:'9px',textAlign:'center'}} className="w-5 h-4 rounded-sm cursor-help flex items-center justify-center">{item.updated_by.initial}</span>
                                                        </TooltipTrigger>
                                                        <TooltipContent>
                                                            <p className="text-xs">Diedit oleh: {item.updated_by.name}</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>
                                                <span className="block">{item.updated ? format(new Date(item.updated), "dd MMM yyyy HH:mm") : "-"}</span>
                                            </div>
                                        </td>
                                        <td className="px-3 py-1 text-center w-[80px]">
                                            {editingId === item.id ? (
                                                <Button
                                                    size="sm"
                                                    variant="outline"
                                                    className="h-8 px-2 bg-green-50 text-green-600 hover:bg-green-100 border-green-200"
                                                    onClick={() => handleSave(item.id)}
                                                    disabled={isPending}
                                                >
                                                    {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                                                </Button>
                                            ) : (
                                                <Button
                                                    size="sm"
                                                    variant="ghost"
                                                    className="h-8 w-8 p-0 text-gray-500 hover:text-blue-600"
                                                    onClick={() => handleEdit(item)}
                                                >
                                                    <Pencil className="w-4 h-4" />
                                                </Button>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
