import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from "dayjs";
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
import {useRouter} from "next/router";
import { fetch } from '../../stores/matters/mattersSlice'
import dataFormatter from '../../helpers/dataFormatter';
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 BaseDivider from "../../components/BaseDivider";
import {
  mdiChartTimelineVariant,
  mdiViewDashboard,
  mdiAccountGroup,
  mdiFileDocument,
  mdiRobot,
  mdiGavel,
  mdiTimelineClock,
  mdiClockTimeFourOutline,
  mdiMagnify
} from "@mdi/js";
import FormField from "../../components/FormField";
import MatterAssistant from "../../components/Matters/MatterAssistant";
import CardBoxModal from "../../components/CardBoxModal";
import axios from 'axios';

const MattersView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { matters } = useAppSelector((state) => state.matters)
    const { id } = router.query;
    const [activeTab, setActiveTab] = useState('overview');
    
    // Analysis State
    const [isAnalyzeModalOpen, setIsAnalyzeModalOpen] = useState(false);
    const [selectedFileForAnalysis, setSelectedFileForAnalysis] = useState<any>(null);
    const [analysisType, setAnalysisType] = useState('summary');
    const [isAnalyzing, setIsAnalyzing] = useState(false);

    useEffect(() => {
        if (id) {
            dispatch(fetch({ id }));
        }
    }, [dispatch, id]);

    const tabs = [
        { id: 'overview', label: 'Overview', icon: mdiViewDashboard },
        { id: 'parties', label: 'Parties', icon: mdiAccountGroup },
        { id: 'documents', label: 'Documents', icon: mdiFileDocument },
        { id: 'ai', label: 'AI & Research', icon: mdiRobot },
        { id: 'simulations', label: 'Simulations', icon: mdiGavel },
        { id: 'timeline', label: 'Timeline', icon: mdiTimelineClock },
    ];

    const openAnalyzeModal = (e: React.MouseEvent, file: any) => {
        e.stopPropagation();
        setSelectedFileForAnalysis(file);
        setIsAnalyzeModalOpen(true);
    };

    const handleAnalyzeConfirm = async () => {
        if (!selectedFileForAnalysis) return;
        setIsAnalyzing(true);
        try {
            await axios.post('/file_extractions/analyze', {
                fileId: selectedFileForAnalysis.id,
                extractionType: analysisType
            });
            setIsAnalyzeModalOpen(false);
            // Optionally notify user
            if (id) dispatch(fetch({ id })); 
        } catch (err: any) {
            console.error(err);
            alert('Analysis failed: ' + (err.response?.data?.message || err.message));
        } finally {
            setIsAnalyzing(false);
        }
    };

    if (!matters) return <div>Loading...</div>;

    return (
      <>
          <Head>
              <title>{getPageTitle(`Case: ${matters.title || 'Loading...'}`)}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton 
                icon={mdiChartTimelineVariant} 
                title={`Case Workspace: ${matters.title || 'Untitled Case'}`} 
                main
            >
                <BaseButton
                  color='info'
                  label='Edit Case Details'
                  href={`/matters/matters-edit/?id=${id}`}
                />
            </SectionTitleLineWithButton>

            {/* Tabs Navigation */}
            <div className="flex flex-wrap gap-2 mb-6">
                {tabs.map((tab) => (
                    <BaseButton
                        key={tab.id}
                        label={tab.label}
                        icon={tab.icon}
                        color={activeTab === tab.id ? 'info' : 'white'}
                        onClick={() => setActiveTab(tab.id)}
                        className={`mb-2 ${activeTab === tab.id ? 'font-bold ring-2 ring-blue-500' : ''}`}
                    />
                ))}
            </div>

            {/* TAB: OVERVIEW */}
            {activeTab === 'overview' && (
                <CardBox>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="md:col-span-2">
                             <h3 className="text-xl font-bold mb-4 border-b pb-2">Case Summary</h3>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Title</p>
                            <p className="text-lg">{matters?.title}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Owner</p>
                            <p>{matters?.owner?.firstName} {matters?.owner?.lastName}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Type</p>
                            <p className="capitalize">{matters?.matter_type?.replace('_', ' ') ?? 'No data'}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Status</p>
                            <span className={`px-2 py-1 rounded text-white text-sm ${matters?.status === 'active' ? 'bg-green-500' : 'bg-gray-500'}`}>
                                {matters?.status ?? 'No data'}
                            </span>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Jurisdiction</p>
                            <p>{matters?.jurisdiction ?? 'N/A'}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Court Name</p>
                            <p>{matters?.court_name ?? 'N/A'}</p>
                        </div>

                        <div className={'mb-4'}>
                            <p className={'block font-bold mb-1 text-gray-500 text-sm'}>Case Number</p>
                            <p>{matters?.case_number ?? 'N/A'}</p>
                        </div>

                         <div className={'mb-4'}>
                             {/* Placeholder for spacer */}
                        </div>

                        <FormField label='Filed At'>
                            {matters.filed_at ? <DatePicker
                              dateFormat="yyyy-MM-dd hh:mm"
                              showTimeSelect
                              selected={new Date(dayjs(matters.filed_at).format('YYYY-MM-DD hh:mm'))}
                              disabled
                              className="w-full bg-gray-100 border-gray-300 rounded"
                            /> : <p>No Date</p>}
                        </FormField>

                        <FormField label='Next Hearing'>
                            {matters.next_hearing_at ? <DatePicker
                              dateFormat="yyyy-MM-dd hh:mm"
                              showTimeSelect
                              selected={new Date(dayjs(matters.next_hearing_at).format('YYYY-MM-DD hh:mm'))}
                              disabled
                              className="w-full bg-gray-100 border-gray-300 rounded"
                            /> : <p>No Hearing Scheduled</p>}
                        </FormField>

                        <div className="md:col-span-2 mt-4">
                            <h3 className="text-xl font-bold mb-4 border-b pb-2">Notes</h3>
                             <div className={'mb-4 bg-gray-50 p-4 rounded border'}>
                                {matters.notes
                                    ? <div dangerouslySetInnerHTML={{__html: matters.notes}}/>
                                    : <p className="text-gray-400 italic">No notes added.</p>
                                }
                            </div>
                        </div>
                    </div>
                </CardBox>
            )}

            {/* TAB: PARTIES */}
            {activeTab === 'parties' && (
                <>
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-xl font-bold">Involved Parties</h3>
                        <BaseButton label="Add Party" color="info" icon={mdiAccountGroup} href="/matter_parties/matter_parties-new" />
                    </div>
                    <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                        <div className='overflow-x-auto'>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Role</th>
                                        <th>Name</th>
                                        <th>Organization</th>
                                        <th>Email</th>
                                        <th>Phone</th>
                                        <th>Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                {matters.matter_parties_matter && Array.isArray(matters.matter_parties_matter) &&
                                  matters.matter_parties_matter.map((item: any) => (
                                    <tr key={item.id} onClick={() => router.push(`/matter_parties/matter_parties-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                        <td data-label="Role" className="capitalize font-medium">{item.party_role?.replace('_', ' ')}</td>
                                        <td data-label="Name">{item.display_name}</td>
                                        <td data-label="Organization">{item.organization_name}</td>
                                        <td data-label="Email">{item.email}</td>
                                        <td data-label="Phone">{item.phone}</td>
                                        <td data-label="Address">{item.address}</td>
                                    </tr>
                                  ))}
                                </tbody>
                            </table>
                        </div>
                        {!matters?.matter_parties_matter?.length && <div className={'text-center py-8 text-gray-500'}>No parties added to this case yet.</div>}
                    </CardBox>
                </>
            )}

            {/* TAB: DOCUMENTS */}
            {activeTab === 'documents' && (
                <>
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-xl font-bold">Case Documents</h3>
                        <BaseButton label="Upload Document" color="info" icon={mdiFileDocument} href="/files/files-new" />
                    </div>
                    <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                        <div className='overflow-x-auto'>
                            <table>
                                <thead>
                                    <tr>
                                        <th>File Name</th>
                                        <th>Type</th>
                                        <th>Size</th>
                                        <th>Status</th>
                                        <th>Uploaded</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                {matters.files_matter && Array.isArray(matters.files_matter) &&
                                  matters.files_matter.map((item: any) => (
                                    <tr key={item.id} onClick={() => router.push(`/files/files-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                        <td data-label="Name" className="font-medium text-blue-600">{item.file_name}</td>
                                        <td data-label="Type">{item.content_type}</td>
                                        <td data-label="Size">{(item.size_bytes / 1024).toFixed(2)} KB</td>
                                        <td data-label="Status">{item.processing_status}</td>
                                        <td data-label="Uploaded">{dataFormatter.dateTimeFormatter(item.uploaded_at)}</td>
                                        <td data-label="Actions" onClick={(e) => e.stopPropagation()}>
                                            <BaseButton 
                                                icon={mdiMagnify} 
                                                small 
                                                color="info" 
                                                onClick={(e) => openAnalyzeModal(e, item)} 
                                                label="Analyze"
                                            />
                                        </td>
                                    </tr>
                                  ))}
                                </tbody>
                            </table>
                        </div>
                        {!matters?.files_matter?.length && <div className={'text-center py-8 text-gray-500'}>No documents uploaded.</div>}
                    </CardBox>
                </>
            )}

            {/* TAB: AI & RESEARCH */}
            {activeTab === 'ai' && (
                <>
                    <div className="mb-6">
                        <MatterAssistant matter={matters} />
                    </div>

                    <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
                        {/* Assistant Threads */}
                        <div>
                            <div className="flex justify-between items-center mb-2">
                                <h4 className="text-lg font-bold">AI Conversations</h4>
                                <BaseButton label="New Chat" small color="info" outline icon={mdiRobot} href="/assistant_threads/assistant_threads-new" />
                            </div>
                            <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                                <div className='overflow-x-auto'>
                                    <table>
                                        <thead><tr><th>Title</th><th>Last Active</th></tr></thead>
                                        <tbody>
                                        {matters.assistant_threads_matter?.map((item: any) => (
                                            <tr key={item.id} onClick={() => router.push(`/assistant_threads/assistant_threads-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                                <td>{item.title}</td>
                                                <td>{dataFormatter.dateTimeFormatter(item.last_activity_at)}</td>
                                            </tr>
                                        ))}
                                        </tbody>
                                    </table>
                                </div>
                                {!matters?.assistant_threads_matter?.length && <div className={'text-center py-4 text-gray-400 text-sm'}>No conversations.</div>}
                            </CardBox>
                        </div>

                         {/* Research Queries */}
                        <div>
                            <div className="flex justify-between items-center mb-2">
                                <h4 className="text-lg font-bold">Research Queries</h4>
                                <BaseButton label="New Query" small color="info" outline href="/research_queries/research_queries-new" />
                            </div>
                            <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                                <div className='overflow-x-auto'>
                                    <table>
                                        <thead><tr><th>Query</th><th>Jurisdiction</th></tr></thead>
                                        <tbody>
                                        {matters.research_queries_matter?.map((item: any) => (
                                            <tr key={item.id} onClick={() => router.push(`/research_queries/research_queries-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                                <td className="truncate max-w-xs">{item.query_text}</td>
                                                <td>{item.jurisdiction}</td>
                                            </tr>
                                        ))}
                                        </tbody>
                                    </table>
                                </div>
                                {!matters?.research_queries_matter?.length && <div className={'text-center py-4 text-gray-400 text-sm'}>No research queries.</div>}
                            </CardBox>
                        </div>
                    </div>

                    {/* Generated Documents */}
                    <div className="mt-4">
                        <h4 className="text-lg font-bold mb-2">Generated Drafts</h4>
                        <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                            <div className='overflow-x-auto'>
                                <table>
                                    <thead><tr><th>Title</th><th>Type</th><th>Format</th><th>Last Edited</th></tr></thead>
                                    <tbody>
                                    {matters.generated_documents_matter?.map((item: any) => (
                                        <tr key={item.id} onClick={() => router.push(`/generated_documents/generated_documents-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                            <td>{item.document_title}</td>
                                            <td>{item.document_type}</td>
                                            <td>{item.format}</td>
                                            <td>{dataFormatter.dateTimeFormatter(item.last_edited_at)}</td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            </div>
                            {!matters?.generated_documents_matter?.length && <div className={'text-center py-4 text-gray-400 text-sm'}>No generated documents.</div>}
                        </CardBox>
                    </div>
                </>
            )}

            {/* TAB: SIMULATIONS */}
            {activeTab === 'simulations' && (
                <>
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-xl font-bold">Mock Trials</h3>
                        <BaseButton label="Start Simulation" color="info" icon={mdiGavel} href="/mock_trials/mock_trials-new" />
                    </div>
                    <CardBox className='mb-6 border border-gray-300 rounded overflow-hidden' hasTable>
                        <div className='overflow-x-auto'>
                            <table>
                                <thead><tr><th>Session</th><th>Mode</th><th>Status</th><th>Scheduled</th></tr></thead>
                                <tbody>
                                {matters.mock_trials_matter?.map((item: any) => (
                                    <tr key={item.id} onClick={() => router.push(`/mock_trials/mock_trials-view/?id=${item.id}`)} className="cursor-pointer hover:bg-gray-50">
                                        <td>{item.session_title}</td>
                                        <td>{item.mode}</td>
                                        <td>{item.status}</td>
                                        <td>{dataFormatter.dateTimeFormatter(item.scheduled_at)}</td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                        </div>
                        {!matters?.mock_trials_matter?.length && <div className={'text-center py-8 text-gray-500'}>No mock trials found.</div>}
                    </CardBox>
                </>
            )}

            {/* TAB: TIMELINE */}
            {activeTab === 'timeline' && (
                <>
                    <h3 className="text-xl font-bold mb-4">Case Timeline & Events</h3>
                    
                    <h4 className="text-lg font-semibold mt-4 mb-2">Medical Events</h4>
                    <CardBox className='mb-4 border border-gray-300 rounded overflow-hidden' hasTable>
                        <div className='overflow-x-auto'>
                            <table>
                                <thead><tr><th>Event</th><th>Date</th></tr></thead>
                                <tbody>
                                {matters.medical_events_matter?.map((item: any) => (
                                    <tr key={item.id} onClick={() => router.push(`/medical_events/medical_events-view/?id=${item.id}`)}>
                                        <td>{item.description || 'No description'}</td>
                                        <td>{dataFormatter.dateTimeFormatter(item.event_date)}</td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                        </div>
                        {!matters?.medical_events_matter?.length && <div className={'text-center py-2 text-gray-400 text-sm'}>No medical events.</div>}
                    </CardBox>

                    <h4 className="text-lg font-semibold mt-4 mb-2">Audit Logs</h4>
                    <CardBox className='mb-4 border border-gray-300 rounded overflow-hidden' hasTable>
                        <div className='overflow-x-auto'>
                            <table>
                                <thead><tr><th>Event</th><th>Category</th><th>Occurred</th></tr></thead>
                                <tbody>
                                {matters.audit_events_matter?.map((item: any) => (
                                    <tr key={item.id} onClick={() => router.push(`/audit_events/audit_events-view/?id=${item.id}`)}>
                                        <td>{item.event_name}</td>
                                        <td>{item.event_category}</td>
                                        <td>{dataFormatter.dateTimeFormatter(item.occurred_at)}</td>
                                    </tr>
                                ))}
                                </tbody>
                            </table>
                        </div>
                        {!matters?.audit_events_matter?.length && <div className={'text-center py-2 text-gray-400 text-sm'}>No audit events.</div>}
                    </CardBox>
                </>
            )}

            <CardBoxModal
                title="Analyze Document"
                buttonColor="info"
                buttonLabel={isAnalyzing ? "Analyzing..." : "Run Analysis"}
                isActive={isAnalyzeModalOpen}
                onConfirm={handleAnalyzeConfirm}
                onCancel={() => setIsAnalyzeModalOpen(false)}
            >
                <p>Select the type of analysis to perform on <strong>{selectedFileForAnalysis?.file_name}</strong>:</p>
                <div className="mt-4">
                    <label className="block mb-2 font-bold">Analysis Type</label>
                    <select 
                        className="w-full border border-gray-300 rounded p-2 bg-white"
                        value={analysisType}
                        onChange={(e) => setAnalysisType(e.target.value)}
                    >
                        <option value="summary">Summarize Document</option>
                        <option value="dates">Extract Key Dates</option>
                        <option value="entities">Extract Entities (People, Orgs)</option>
                        <option value="issues">Identify Legal Issues</option>
                        <option value="clauses">Extract Clauses</option>
                        <option value="citations">Extract Citations</option>
                    </select>
                    <p className="text-sm text-gray-500 mt-2">
                        Supported file types: Text-based files (TXT, CSV, MD, JSON) and PDF.
                    </p>
                </div>
            </CardBoxModal>

          </SectionMain>
      </>
    );
};

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

export default MattersView;