import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head'
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
import {useRouter} from "next/router";
import { fetch } from '../../stores/mock_trials/mock_trialsSlice'
import LayoutAuthenticated from "../../layouts/Authenticated";
import {getPageTitle} from "../../config";
import SectionTitleLineWithButton from "../../components/SectionTitleLineWithButton";
import SectionMain from "../../components/SectionMain";
import CardBox from "../../components/CardBox";
import BaseButton from "../../components/BaseButton";
import {mdiAccount, mdiGavel, mdiPlay} from "@mdi/js";
import axios from 'axios';
import BaseIcon from "../../components/BaseIcon";

const MockTrialSimulator = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { mock_trials } = useAppSelector((state) => state.mock_trials)
    const { id } = router.query;
    const [generating, setGenerating] = useState(false);

    useEffect(() => {
        if (id) {
            dispatch(fetch({ id }));
        }
    }, [dispatch, id, generating]); // Refresh when generating done

    const handleGenerateTurn = async () => {
        setGenerating(true);
        try {
            await axios.post(`/mock_trials/${id}/generate-turn`);
            // dispatch(fetch({ id })); // Triggered by dependency
        } catch (error) {
            console.error("Failed to generate turn", error);
            alert("Failed to generate turn. Please try again.");
        } finally {
            setGenerating(false);
        }
    };

    if (!mock_trials) return null;

    const roles = mock_trials.mock_trial_roles_mock_trial || [];
    const turns = mock_trials.mock_trial_turns_mock_trial || [];
    // Sort turns by spoken_at asc
    const sortedTurns = [...turns].sort((a: any, b: any) => new Date(a.spoken_at).getTime() - new Date(b.spoken_at).getTime());

    return (
      <>
          <Head>
              <title>{getPageTitle('Mock Trial Simulator')}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiGavel} title={`Simulation: ${mock_trials.session_title}`} main>
                <BaseButton
                  color='info'
                  label='Edit Settings'
                  href={`/mock_trials/mock_trials-edit/?id=${id}`}
                  outline
                />
            </SectionTitleLineWithButton>

            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
                {/* Left: Roles */}
                <div className="lg:col-span-1 space-y-4">
                    <CardBox className="h-full">
                        <h3 className="font-bold text-lg mb-4 border-b pb-2">Participants</h3>
                        <div className="space-y-3">
                            {roles.map((role: any) => (
                                <div key={role.id} className="flex items-center p-2 rounded bg-gray-50 dark:bg-slate-800">
                                    <div className="bg-blue-100 text-blue-600 rounded-full p-2 mr-3">
                                        <BaseIcon path={mdiAccount} size={20} />
                                    </div>
                                    <div>
                                        <p className="font-semibold text-sm">{role.role_name}</p>
                                        <p className="text-xs text-gray-500">{role.display_name}</p>
                                    </div>
                                </div>
                            ))}
                            {roles.length === 0 && <p className="text-gray-500 text-sm">No roles defined.</p>}
                        </div>
                    </CardBox>
                </div>

                {/* Right: Transcript */}
                <div className="lg:col-span-3">
                    <CardBox className="h-[600px] flex flex-col relative">
                        <div className="flex-1 overflow-y-auto space-y-4 p-4">
                            {sortedTurns.map((turn: any) => {
                                const role = roles.find((r: any) => r.id === turn.roleId);
                                const isJudge = role?.role_name?.toLowerCase().includes('judge');
                                return (
                                    <div key={turn.id} className={`flex ${isJudge ? 'justify-center' : 'justify-start'}`}>
                                        <div className={`max-w-[80%] p-4 rounded-lg shadow-sm ${
                                            isJudge ? 'bg-amber-50 border-amber-200 border' : 'bg-white border border-gray-100 dark:bg-slate-700 dark:border-slate-600'
                                        }`}>
                                            <div className="flex items-center mb-1">
                                                <span className="font-bold text-sm mr-2 text-blue-600">
                                                    {role ? role.role_name : 'Unknown'}
                                                </span>
                                                <span className="text-xs text-gray-400 uppercase tracking-wider">
                                                    {turn.turn_type}
                                                </span>
                                            </div>
                                            <p className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap leading-relaxed">
                                                {turn.content}
                                            </p>
                                        </div>
                                    </div>
                                );
                            })}
                            {sortedTurns.length === 0 && (
                                <div className="text-center text-gray-400 mt-20">
                                    <p>No turns yet. Start the simulation.</p>
                                </div>
                            )}
                        </div>
                        
                        {/* Footer Controls */}
                        <div className="border-t p-4 bg-gray-50 dark:bg-slate-800 rounded-b-lg flex justify-between items-center">
                            <div className="text-sm text-gray-500">
                                Status: <span className="font-semibold text-gray-700 dark:text-gray-300 capitalize">{mock_trials.status}</span>
                            </div>
                            <BaseButton
                                color="success"
                                icon={mdiPlay}
                                label={generating ? "Generating..." : "Simulate Next Turn"}
                                onClick={handleGenerateTurn}
                                disabled={generating || roles.length === 0}
                            />
                        </div>
                    </CardBox>
                </div>
            </div>
          </SectionMain>
      </>
    );
};

MockTrialSimulator.getLayout = function getLayout(page: ReactElement) {
    return (
      <LayoutAuthenticated permission={'READ_MOCK_TRIALS'}>
          {page}
      </LayoutAuthenticated>
    )
}

export default MockTrialSimulator;
