import { useEffect, useMemo, useState } from 'react';
import {
  ArrowLeft,
  ArrowRight,
  Briefcase,
  ChevronDown,
  CheckCircle2,
  Clock3,
  Code2,
  Filter,
  Globe,
  Lightbulb,
  Mic,
  MoreHorizontal,
  PauseCircle,
  PlayCircle,
  Radio,
  StopCircle,
  Target,
  UserRound,
} from 'lucide-react';
import { SimulatorViewModel, type SimulatorInterviewItem } from '../../../mvvm/viewmodels/SimulatorViewModel';
import type { JobsListItem } from '../../../mvvm/viewmodels/JobsPageViewModel';
import { DashboardSidebar, type DashboardNavKey } from '../../dashboard/components/DashboardSidebar';
import { DashboardTopbar } from '../../dashboard/components/DashboardTopbar';
import '../../dashboard/pages/dashboard.css';
import './simulator.css';

interface SimulatorPageProps {
  onLogout: () => void;
  onNavigate: (target: DashboardNavKey) => void;
  onOpenEvaluation: (selection: SimulatorEvaluationSelection) => void;
  onToggleTheme: () => void;
  theme: 'light' | 'dark';
}

interface InterviewCard {
  id: string;
  title: string;
  companyName: string;
  completed: boolean;
  durationMinutes: number;
  personality: string;
  dateLabel: string;
}

export interface SimulatorEvaluationSelection {
  interviewId: string;
  title: string;
  companyName: string;
  dateLabel: string;
}

const FALLBACK_INTERVIEWS: InterviewCard[] = [
  {
    id: 'sim-1',
    title: 'Senior Frontend-udvikler',
    companyName: 'Lunar',
    completed: true,
    durationMinutes: 15,
    personality: 'Professionel',
    dateLabel: '12. okt 2023',
  },
  {
    id: 'sim-2',
    title: 'Fullstack Developer',
    companyName: 'Pleo',
    completed: false,
    durationMinutes: 20,
    personality: 'Afslappet',
    dateLabel: '10. okt 2023',
  },
  {
    id: 'sim-3',
    title: 'UX Designer',
    companyName: 'Trustpilot',
    completed: true,
    durationMinutes: 10,
    personality: 'Sarkastisk',
    dateLabel: '05. okt 2023',
  },
  {
    id: 'sim-4',
    title: 'Product Manager',
    companyName: 'Danske Bank',
    completed: true,
    durationMinutes: 5,
    personality: 'Stress-test',
    dateLabel: '01. okt 2023',
  },
];

function toInterviewCard(item: SimulatorInterviewItem): InterviewCard {
  return {
    id: item.id,
    title: item.title,
    companyName: item.companyName,
    completed: item.completed,
    durationMinutes: item.durationMinutes ?? 15,
    personality: item.personality || 'Professionel',
    dateLabel: item.dateLabel || 'Nyligt',
  };
}

function jobLabel(job: JobsListItem): string {
  return `${job.title || 'Stilling'}${job.companyName ? ` · ${job.companyName}` : ''}`;
}

export function SimulatorPage({ onLogout, onNavigate, onOpenEvaluation, onToggleTheme, theme }: SimulatorPageProps) {
  const viewModel = useMemo(() => new SimulatorViewModel(), []);

  const [name, setName] = useState('Lasse');
  const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
  const [jobs, setJobs] = useState<JobsListItem[]>([]);
  const [interviews, setInterviews] = useState<InterviewCard[]>([]);
  const [personalities, setPersonalities] = useState<Array<{ id: number; name: string }>>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [selectedJobId, setSelectedJobId] = useState('');
  const [selectedPersonalityId, setSelectedPersonalityId] = useState('');
  const [selectedLanguage, setSelectedLanguage] = useState('Dansk');
  const [selectedDuration, setSelectedDuration] = useState('15');
  const [isLiveSession, setIsLiveSession] = useState(false);

  useEffect(() => {
    let active = true;

    async function load() {
      setIsLoading(true);

      const [profile, jobsData, interviewData, personalityData] = await Promise.all([
        viewModel.getCandidateProfile(),
        viewModel.getJobs(),
        viewModel.getInterviews(),
        viewModel.getPersonalities(),
      ]);

      if (!active) {
        return;
      }

      setName(profile.name);
      setImageUrl(profile.imageUrl);
      setJobs(jobsData);
      setInterviews(interviewData.map(toInterviewCard));
      setPersonalities(personalityData.map((item) => ({ id: item.id, name: item.name })));

      if (jobsData.length > 0) {
        setSelectedJobId((current) => current || jobsData[0].id);
      }

      if (personalityData.length > 0) {
        setSelectedPersonalityId((current) => current || String(personalityData[0].id));
      }

      setIsLoading(false);
    }

    void load();

    return () => {
      active = false;
    };
  }, [viewModel]);

  const cards = interviews.length > 0 ? interviews : FALLBACK_INTERVIEWS;
  const fallbackJob = { id: 'fallback-job', title: 'Senior Frontend-udvikler', companyName: 'Lunar' } as JobsListItem;
  const jobOptions = jobs.length > 0 ? jobs : [fallbackJob];
  const activeJob = jobOptions.find((job) => job.id === selectedJobId) || jobOptions[0];
  const activePersonality = personalities.find((item) => String(item.id) === selectedPersonalityId)?.name || 'Professionel & Grundig';

  const liveMessages = [
    {
      id: 'ai-1',
      sender: 'ai',
      text:
        'Hej Lasse, og velkommen til! Vi er rigtig glade for at have dig til samtalen omkring rollen som '
        + `${activeJob.title || 'Senior Frontend-udvikler'}. Kan du fortælle om et nyligt projekt, `
        + 'hvor din erfaring med React gjorde en stor forskel for slutresultatet?',
    },
    {
      id: 'me-1',
      sender: 'me',
      text:
        'I mit seneste projekt migrerede vi en stor dashboard-løsning til Next.js. '
        + 'Jeg implementerede virtualisering og strammere state management med Zustand, '
        + 'hvilket reducerede load-tid med over 60%.',
    },
    {
      id: 'ai-2',
      sender: 'ai',
      text:
        'Det lyder som en rigtig solid forbedring. Når du nævner Zustand frem for Redux, '
        + 'hvad var overvejelserne bag det valg i jeres use-case?',
    },
  ] as const;

  return (
    <section className={`dash-root ${theme === 'dark' ? 'theme-dark' : ''}`}>
      <div className="dash-orb dash-orb-1" />
      <div className="dash-orb dash-orb-2" />
      <div className="dash-orb dash-orb-3" />

      <DashboardSidebar active="simulator" onNavigate={onNavigate} />

      <main className="dash-main custom-scrollbar sim-main">
        <DashboardTopbar
          name={name}
          imageUrl={imageUrl}
          onLogout={onLogout}
          theme={theme}
          onToggleTheme={onToggleTheme}
          actions={isLiveSession ? (
            <button type="button" className="sim-leave-btn" onClick={() => setIsLiveSession(false)}>
              <ArrowLeft size={15} strokeWidth={1.8} />
              <span>Forlad simulering</span>
            </button>
          ) : undefined}
        />

        {isLiveSession ? (
          <div className="sim-live-wrap">
            <div className="sim-live-head">
              <h1>Live Jobsamtale</h1>
              <p>Du er i øjeblikket i en simuleret teknisk samtale. Brug mikrofonen til at svare.</p>
            </div>

            <div className="sim-live-grid">
              <section className="sim-live-chat-card">
                <div className="sim-live-chat-head">
                  <div className="sim-live-ai-row">
                    <div className="sim-live-ai-avatar"><UserRound size={18} strokeWidth={1.8} /></div>
                    <div>
                      <h3>Sarah (AI Interviewer)</h3>
                      <p><Radio size={12} strokeWidth={1.8} /> Venter på dit svar...</p>
                    </div>
                  </div>
                  <button type="button" className="sim-live-more-btn"><MoreHorizontal size={16} strokeWidth={1.8} /></button>
                </div>

                <div className="sim-live-chat-scroll custom-scrollbar">
                  {liveMessages.map((message) => (
                    <div
                      key={message.id}
                      className={message.sender === 'ai' ? 'sim-live-msg-row ai' : 'sim-live-msg-row me'}
                    >
                      <div className={message.sender === 'ai' ? 'sim-live-msg-avatar ai' : 'sim-live-msg-avatar me'}>
                        {message.sender === 'ai'
                          ? <UserRound size={13} strokeWidth={1.8} />
                          : (imageUrl ? <img src={imageUrl} alt={name} /> : <span>{name.slice(0, 1).toUpperCase()}</span>)}
                      </div>
                      <div className={message.sender === 'ai' ? 'sim-live-msg-bubble ai' : 'sim-live-msg-bubble me'}>
                        <p>{message.text}</p>
                      </div>
                    </div>
                  ))}
                </div>

                <div className="sim-live-voice">
                  <div className="sim-live-time-row">
                    <div className="sim-live-time">
                      <small>Tid gået</small>
                      <strong>04:23</strong>
                    </div>
                    <div className="sim-live-wave">
                      {Array.from({ length: 7 }).map((_, index) => (
                        <span key={`wave-${index}`} style={{ animationDelay: `${index * 0.14}s` }} />
                      ))}
                    </div>
                    <div className="sim-live-time">
                      <small>Tilbage</small>
                      <strong>10:37</strong>
                    </div>
                  </div>

                  <button type="button" className="sim-live-mic-btn">
                    <Mic size={22} strokeWidth={1.8} />
                  </button>
                  <p>Optager dit svar...</p>
                </div>
              </section>

              <aside className="sim-live-side custom-scrollbar">
                <article className="sim-live-side-card">
                  <h2>Session Status</h2>
                  <div className="sim-live-side-list">
                    <div>
                      <small>Stilling</small>
                      <p>{activeJob.title || 'Senior Frontend-udvikler'} @ {activeJob.companyName || 'Lunar'}</p>
                    </div>
                    <div>
                      <small>Samtaletype</small>
                      <p><Code2 size={14} strokeWidth={1.8} /> Teknisk Dybde</p>
                    </div>
                    <div>
                      <small>Interviewer stil</small>
                      <p><UserRound size={14} strokeWidth={1.8} /> {activePersonality}</p>
                    </div>
                    <div>
                      <div className="sim-live-progress-head">
                        <small>Fremgang</small>
                        <strong>Spørgsmål 2 af 5</strong>
                      </div>
                      <div className="sim-live-progress-track"><span /></div>
                    </div>
                  </div>
                </article>

                <article className="sim-live-coach-card">
                  <h2><Lightbulb size={15} strokeWidth={1.8} /> Live Coach</h2>
                  <div className="sim-live-coach-list">
                    <div>
                      <CheckCircle2 size={14} strokeWidth={1.8} />
                      <div>
                        <strong>Godt brug af STAR-metoden</strong>
                        <p>Dit forrige svar beskrev situationen og resultatet meget tydeligt.</p>
                      </div>
                    </div>
                    <div>
                      <Target size={14} strokeWidth={1.8} />
                      <div>
                        <strong>Næste skridt</strong>
                        <p>Uddyb hvorfor Zustand var bedre end Redux i jeres specifikke use-case.</p>
                      </div>
                    </div>
                  </div>
                </article>

                <article className="sim-live-side-card">
                  <div className="sim-live-actions">
                    <button type="button"><PauseCircle size={16} strokeWidth={1.8} /> Sæt på pause</button>
                    <button type="button" className="stop"><StopCircle size={16} strokeWidth={1.8} /> Afslut & Få Feedback</button>
                  </div>
                </article>
              </aside>
            </div>
          </div>
        ) : (
          <div className="sim-wrap">
            <section className="sim-hero-card">
              <div className="sim-hero-glow" />

              <div className="sim-hero-left">
                <h1>Job Interview Simulator</h1>
                <p>
                  Ov dig pa jobsamtaler med vores AI-drevne simulator. Du far skraeddersyede sporgsmal
                  baseret pa den jobtype, du soger, og modtager detaljeret feedback pa dine svar.
                </p>

                <ul className="sim-benefits">
                  <li><CheckCircle2 size={16} strokeWidth={1.8} /> Personaliserede interviewsporgsmal</li>
                  <li><CheckCircle2 size={16} strokeWidth={1.8} /> Ojeblikkelig AI-feedback pa dine svar</li>
                  <li><CheckCircle2 size={16} strokeWidth={1.8} /> Detaljeret evaluering efter interviewet</li>
                  <li><CheckCircle2 size={16} strokeWidth={1.8} /> Gem og gennemga tidligere interviews</li>
                </ul>

                <button type="button" className="sim-start-btn" onClick={() => setIsLiveSession(true)}>
                  <PlayCircle size={18} strokeWidth={1.8} />
                  Start ny simulering
                </button>
              </div>

              <div className="sim-config-card">
                <div className="sim-config-head">
                  <h3>Simuleringsindstillinger</h3>
                  <p>Vaelg dine praeferencer for start</p>
                </div>

                <label>
                  Gemt job
                  <div className="sim-select-wrap">
                    <Briefcase size={16} strokeWidth={1.8} />
                    <select value={selectedJobId} onChange={(event) => setSelectedJobId(event.target.value)}>
                      {jobOptions.map((job) => (
                        <option key={job.id} value={job.id}>{jobLabel(job)}</option>
                      ))}
                    </select>
                    <ChevronDown size={15} strokeWidth={1.8} className="sim-caret" />
                  </div>
                </label>

                <label>
                  Personlighed (AI)
                  <div className="sim-select-wrap">
                    <UserRound size={16} strokeWidth={1.8} />
                    <select value={selectedPersonalityId} onChange={(event) => setSelectedPersonalityId(event.target.value)}>
                      {(personalities.length > 0 ? personalities : [{ id: 1, name: 'Professionel & Grundig' }]).map((personality) => (
                        <option key={personality.id} value={String(personality.id)}>{personality.name}</option>
                      ))}
                    </select>
                    <ChevronDown size={15} strokeWidth={1.8} className="sim-caret" />
                  </div>
                </label>

                <div className="sim-mini-grid">
                  <label>
                    Sprog
                    <div className="sim-select-wrap">
                      <Globe size={16} strokeWidth={1.8} />
                      <select value={selectedLanguage} onChange={(event) => setSelectedLanguage(event.target.value)}>
                        <option>Dansk</option>
                        <option>Engelsk</option>
                      </select>
                      <ChevronDown size={15} strokeWidth={1.8} className="sim-caret" />
                    </div>
                  </label>

                  <label>
                    Varighed
                    <div className="sim-select-wrap">
                      <Clock3 size={16} strokeWidth={1.8} />
                      <select value={selectedDuration} onChange={(event) => setSelectedDuration(event.target.value)}>
                        <option value="5">5 min</option>
                        <option value="10">10 min</option>
                        <option value="15">15 min</option>
                        <option value="20">20 min</option>
                      </select>
                      <ChevronDown size={15} strokeWidth={1.8} className="sim-caret" />
                    </div>
                  </label>
                </div>
              </div>
              </section>

              <div className="sim-history-head">
                <h2>Tidligere simuleringer</h2>
                <button type="button"><Filter size={15} strokeWidth={1.8} /> Filtrer</button>
              </div>

              {isLoading ? <p className="dash-loading">Indlaeser simuleringer...</p> : null}

              <section className="sim-history-grid">
                {cards.map((item) => (
                  <article key={item.id} className={item.completed ? 'sim-card done' : 'sim-card draft'}>
                    <div className="sim-card-head">
                      <div>
                        <h3>{item.title}</h3>
                        <p>{item.companyName}</p>
                      </div>
                      <span className={item.completed ? 'sim-status done' : 'sim-status draft'}>
                        {item.completed ? 'Faerdig' : 'Ikke faerdig'}
                      </span>
                    </div>

                    <div className="sim-tags">
                      <span><Clock3 size={13} strokeWidth={1.8} /> {item.durationMinutes} min</span>
                      <span><UserRound size={13} strokeWidth={1.8} /> {item.personality}</span>
                    </div>

                    <div className="sim-card-foot">
                      <small>{item.dateLabel}</small>
                      {item.completed ? (
                        <button
                          type="button"
                          className="sim-link-btn"
                          onClick={() => onOpenEvaluation({
                            interviewId: item.id,
                            title: item.title,
                            companyName: item.companyName,
                            dateLabel: item.dateLabel,
                          })}
                        >
                          Se evaluering <ArrowRight size={14} strokeWidth={1.8} />
                        </button>
                      ) : null}
                    </div>
                  </article>
                ))}
              </section>
            </div>
          )}
      </main>
    </section>
  );
}
