'use client';

import { useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import {
  PiArrowLeft,
  PiEnvelopeSimple,
  PiPhone,
  PiMapPin,
  PiCalendarDot,
  PiSealCheck,
  PiTag,
  PiCaretLeft,
  PiPhoneCall,
  PiRecycle,
  PiTarget,
  PiUser,
  PiTrendUp,
  PiPhoneIncoming,
  PiPhoneOutgoing,
  PiPhoneX,
  PiPhoneSlash,
  PiPhoneDisconnect,
  PiPlus,
  PiNotePencil,
  PiCheckCircle,
} from 'react-icons/pi';
import PrimaryButton from '@/components/common/primary-button';
import ConfirmModal from '@/components/common/confirm-modal';
import ScheduleFollowup from '@/components/modals/manage_lead/ScheduleFollowup';
import user from '../../../../../../public/auh/user_2.png';
import Timeline from '@/components/common/timeline';
import { StaticImageData } from 'next/image';

type LeadStatus =
  | 'New'
  | 'Contacted'
  | 'Qualified'
  | 'Followup'
  | 'Interested'
  | 'Lost'
  | 'Converted';

type Lead = {
  id: number;
  image: string | StaticImageData;
  name: string;
  email: string;
  mobile: string;
  location: string;
  status: LeadStatus;
  score: number;
  source: string;
  assignedTo: string;
  tags: string[];
};

const pipeline = [
  'New',
  'Contacted',
  'Qualified',
  'Followup',
  'Interested',
  'Converted',
];

export default function Page() {
  const router = useRouter();
  const params = useParams();
  const [convertLead, setConvertLead] = useState<Lead | null>(null);
  const [openFollowupModal, setOpenFollowupModal] = useState(false);
  const [note, setNote] = useState('');
  const [timeline, setTimeline] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState('NOTES');

  const [leads] = useState<Lead[]>([
    {
      id: 1,
      image: user,
      name: 'Arjun Kapoor',
      email: 'arjun@hdfc.com',
      mobile: '9876500005',
      location: 'Chennai',
      status: 'Qualified',
      score: 99,
      source: 'website',
      assignedTo: 'Ramesh',
      tags: ['Luxury', 'Penthouse'],
    },
  ]);

  const lead = useMemo(
    () => leads.find((l) => l.id === Number(params.id)),
    [params.id, leads]
  );

  if (!lead) return <div className="p-10">Not found</div>;

  const currentStep = pipeline.indexOf(lead.status);

  const handleConvert = () => {
    console.log('Converted:', convertLead);
    setConvertLead(null);
  };

  const getStatusColor = (status: LeadStatus) => {
    switch (status) {
      case 'New':
        return 'bg-blue-100 text-blue-600';
      case 'Contacted':
        return 'bg-yellow-100 text-yellow-600';
      case 'Followup':
        return 'bg-purple-100 text-purple-600';
      case 'Interested':
        return 'bg-cyan-100 text-cyan-600';
      case 'Lost':
        return 'bg-red-100 text-red-600';
      case 'Converted':
        return 'bg-emerald-100 text-emerald-600';
      default:
        return 'bg-gray-100 text-gray-600';
    }
  };

  const timelineItems = [
    {
      id: 1,
      title: 'Current User',
      subtitle: 'FOLLOW UP SET',
      description:
        'Scheduled follow-up for 2026-05-15 at 07:47. Reminder: No specific notes.',
      date: '20/05/2026, 15:43:16',
      icon: <PiCalendarDot className="text-blue-600" />,
    },
    {
      id: 2,
      title: 'Rohit Sharma',
      subtitle: 'MEETING',
      description:
        'In-person meeting at HQ. Showcased the penthouse model. Client impressed with the ceiling height.',
      date: '2023-10-26 11:00 AM',
      icon: <PiPhoneCall className="text-green-600" />,
    },
  ];

  const handleAddLog = () => {
    if (!note.trim()) return;

    const newLog = {
      id: Date.now(),
      message: note,
      createdAt: new Date().toLocaleString(),
    };

    setTimeline((prev) => [newLog, ...prev]);
    setNote('');
  };

  const callHistory = [
    {
      id: 1,
      type: 'Incoming',
      agent: 'Rajesh',
      duration: '05:24',
      time: '25-Mar-2026 05:45 PM',
      icon: <PiPhoneIncoming className="text-green-600 text-lg" />,
      color: 'text-green-600',
      bg: 'bg-green-50',
    },
    {
      id: 2,
      type: 'Outgoing',
      agent: 'Karthik',
      duration: '02:10',
      time: '25-Mar-2026 04:20 PM',
      icon: <PiPhoneOutgoing className="text-blue-600 text-lg" />,
      color: 'text-blue-600',
      bg: 'bg-blue-50',
    },
    {
      id: 3,
      type: 'Missed',
      agent: 'Vijay',
      duration: '00:00',
      time: '25-Mar-2026 03:15 PM',
      icon: <PiPhoneX className="text-red-600 text-lg" />,
      color: 'text-red-600',
      bg: 'bg-red-50',
    },
    {
      id: 4,
      type: 'Rejected',
      agent: 'Arun',
      duration: '00:00',
      time: '25-Mar-2026 02:40 PM',
      icon: <PiPhoneSlash className="text-orange-600 text-lg" />,
      color: 'text-orange-600',
      bg: 'bg-orange-50',
    },
    {
      id: 5,
      type: 'Not Answered',
      agent: 'Suresh',
      duration: '00:00',
      time: '25-Mar-2026 01:05 PM',
      icon: <PiPhoneDisconnect className="text-gray-600 text-lg" />,
      color: 'text-gray-600',
      bg: 'bg-gray-100',
    },
  ];

  const tabs = [
    { label: 'NOTES', icon: <PiNotePencil /> },
    { label: 'CALL LOG', icon: <PiPhoneCall /> },
  ];

  return (
    <>
      {/* HEADER */}
      <div className="flex justify-between items-center p-4 border-b">
        <div className="flex items-center gap-3">
          <button onClick={() => router.back()}>
            <PiCaretLeft />
          </button>
          <div>
            <h2 className="text-xl font-semibold">{lead.name}</h2>
            <div className="flex items-center gap-2 justify-start">
              <span className="text-sm text-gray-500 flex items-center gap-1">
                <PiPhoneCall className='text-primary font-semibold'/>{lead.mobile}
              </span>
              <span className="text-sm text-gray-500 flex items-center gap-1">
                •
              </span>
              <span className="text-sm text-gray-500 flex items-center gap-1">
                <PiEnvelopeSimple className='text-primary font-semibold'/>{lead.email}
              </span>
            </div>
          </div>
        </div>
        <PrimaryButton onClick={() => setConvertLead(lead)}>
          Convert to Customer
        </PrimaryButton>
      </div>
      <div className="px-10 py-6 border-b">
        <div className="relative flex justify-between items-center">
          <div className="absolute top-4 left-0 right-0 h-1 bg-gray-200 z-0" />
          <div
            className="absolute top-4 left-0 h-1 bg-green-500 z-0 transition-all"
            style={{
              width: `${(currentStep / (pipeline.length - 1)) * 100}%`,
            }}
          />
          {pipeline.map((step, i) => {
            const isCompleted = i < currentStep;
            const isCurrent = i === currentStep;
            return (
              <div
                key={step}
                className="relative z-10 flex flex-col items-center text-xs w-full"
              >
                <div
                  className={`h-8 w-8 flex items-center justify-center rounded-full border-2 transition-all
                    ${
                      isCompleted
                        ? 'bg-green-500 border-green-500 text-white'
                        : isCurrent
                        ? 'bg-primary border-primary text-white scale-110'
                        : 'bg-white border-gray-300 text-gray-400'
                    }
                  `}
                >
                  {i + 1}
                </div>
                <span
                  className={`mt-2 text-xs font-medium
                    ${
                      isCompleted
                        ? 'text-green-600'
                        : isCurrent
                        ? 'text-primary font-semibold'
                        : 'text-gray-400'
                    }
                  `}
                >
                  {step}
                </span>
              </div>
            );
          })}
        </div>
      </div>
      <div className="grid grid-cols-12 gap-6 p-6">
        <div className="col-span-3 bg-white border rounded-xl p-4">
          <div className="flex flex-col items-center mb-2">
            <Image
              src={typeof lead.image === 'string' ? lead.image : lead.image.src}
              alt={lead.name}
              width={40}
              height={40}
              className="rounded-full border"
            />
            <h3 className="mt-2 text-lg font-semibold">{lead.name}</h3>
            <span
              className={`px-3 py-1 text-xs rounded-full font-medium ${getStatusColor(
                lead.status
              )}`}
            >
              {lead.status}
            </span>
          </div>
          <hr></hr>
          <div className="mt-4 space-y-3 text-sm">
            <h5 className="text-xs text-gray-500 mb-2">Contact Info</h5>
            <div className="flex items-center gap-2">
              <PiEnvelopeSimple /> {lead.email}
            </div>
            <div className="flex items-center gap-2">
              <PiPhone /> +91 {lead.mobile}
            </div>
            <div className="flex items-center gap-2">
              <PiMapPin /> {lead.location}
            </div>
          </div>
          <div className="mt-4 space-y-3 text-sm">
            <h5 className="text-xs text-gray-500 mb-2">Key Info</h5>
            <div className="grid grid-cols-2 gap-2">
              <div className="flex items-center gap-1 rounded bg-gray-100 p-2">
                <PiTarget />
                <span className='text-gray-700 font-semibold'>{lead.source}</span>
              </div>
              <div className="flex items-center gap-1 rounded bg-gray-100 p-2">
                <PiUser />
                <span className='text-gray-700 font-semibold'>{lead.assignedTo}</span>
              </div>
            </div>
          </div>
          <div className="mt-4">
            <h5 className="text-xs text-gray-500 mb-2">Tags</h5>
            <div className="flex flex-wrap gap-2">
              {lead.tags.map((tag) => (
                <span
                  key={tag}
                  className="bg-gray-100 px-2 py-1 rounded text-xs flex items-center gap-2"
                >
                  <PiTag />
                  {tag}
                </span>
              ))}
            </div>
          </div>
        </div>
        <div className="col-span-6 space-y-4">
          <div className="bg-white border rounded-xl p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex gap-2">
                {tabs.map((tab) => {
                  const isActive = activeTab === tab.label;

                  return (
                    <button
                      key={tab.label}
                      onClick={() => setActiveTab(tab.label)}
                      className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full font-medium transition-all
                        ${
                          isActive
                            ? 'bg-blue-100 text-blue-600 ring-1 ring-blue-300'
                            : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                        }`}
                    >
                      <span className="text-sm">{tab.icon}</span>
                      {tab.label}
                    </button>
                  );
                })}
              </div>
              <button
                onClick={() => setOpenFollowupModal(true)}
                className="text-sm text-blue-600 font-medium flex items-center gap-1"
              >
                <PiPlus/>Set Follow-up
              </button>
            </div>
            <div className="border rounded-xl bg-gray-50 p-3">
              <textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="What is the status of this note?"
                className="w-full bg-transparent outline-none text-sm resize-none"
                rows={4}
              />
            </div>
            <div className="flex items-center justify-end mt-3">
              <PrimaryButton onClick={handleAddLog}>
                Record Event
              </PrimaryButton>
            </div>
          </div>
          <div className="flex items-center justify-between px-1">
            <div className="flex items-center gap-2">
              <div className="h-8 w-8 flex items-center justify-center bg-blue-100 rounded-md">
                <PiTrendUp className='text-lg text-primary font-semibold'/>
              </div>
              <h4 className="font-semibold text-sm">
                Full Engagement Timeline
              </h4>
            </div>
            <span className="text-xs text-gray-500">
              {timelineItems.length} Records
            </span>
          </div>
          <div className="bg-white border rounded-xl py-4 px-8">
            <Timeline items={timelineItems} />
          </div>
        </div>

        <div className="col-span-3 space-y-4">
          <div className="bg-white border rounded-xl p-4">
            <h5 className="text-xs text-gray-500">Lead Score</h5>
            <div className="text-3xl font-bold text-green-600">
              {lead.score}
            </div>
            <div className="h-2 bg-gray-200 rounded mt-2">
              <div
                className="h-2 bg-green-500 rounded"
                style={{ width: `${lead.score}%` }}
              />
            </div>
          </div>
          <div className="bg-white border rounded-xl p-4">
            <h5 className="text-xs text-gray-500">Call History</h5>
            <div className="mt-3 space-y-3 max-h-64 overflow-auto">
              {callHistory.map((call) => (
                <div
                  key={call.id}
                  className={`p-3 border rounded-lg flex justify-between items-center ${call.bg}`}
                >
                  <div className="flex items-center gap-3">
                    <div className="bg-white p-2 rounded-full shadow-sm">
                      {call.icon}
                    </div>

                    <div className="flex flex-col">
                      <span className={`font-medium ${call.color}`}>
                        {call.type}
                      </span>
                      <span className="text-gray-500 text-sm">
                        {call.time}
                      </span>
                    </div>
                  </div>

                  <div className="flex flex-col items-end">
                    <span className={`font-semibold ${call.color}`}>
                      {call.duration}
                    </span>
                    <span className="text-secondary text-sm">
                      {call.agent}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* MODALS */}
      <ScheduleFollowup
        open={openFollowupModal}
        onClose={() => setOpenFollowupModal(false)}
        leadData={lead}
        onSubmit={(data: any) => console.log(data)}
      />

      <ConfirmModal
        open={!!convertLead}
        onClose={() => setConvertLead(null)}
        onConfirm={handleConvert}
        title="Convert to Customer"
        description={`Are you sure you want to convert "${convertLead?.name}" to customer?`}
        confirmText="Yes, Convert"
        confirmColor="bg-emerald-500 hover:bg-emerald-600"
      />
    </>
  );
}