import { mdiGavel, mdiMagnify, mdiScaleBalance } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useState } from 'react'
import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'
import BaseButton from '../../components/BaseButton'
import FormField from '../../components/FormField'
import axios from 'axios'
import BaseDivider from '../../components/BaseDivider'

const AdvancedLegalResearch = () => {
  const [query, setQuery] = useState('')
  const [jurisdiction, setJurisdiction] = useState('')
  const [scope, setScope] = useState('federal')
  const [results, setResults] = useState<any[] | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleSearch = async (e) => {
    e.preventDefault();
    if (!query) return;

    setLoading(true);
    setResults(null);
    setError('');

    try {
      const response = await axios.post('/research_queries/search', {
        data: {
            query_text: query,
            jurisdiction,
            source_scope: scope
        }
      });
      setResults(response.data.results);
    } catch (err) {
      console.error(err);
      setError('Search failed. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Advanced Legal Research')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiScaleBalance} title="Advanced Legal Research" main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className="mb-6">
          <form onSubmit={handleSearch}>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div className="md:col-span-2">
                <FormField label="Legal Query">
                  <input
                    className="w-full px-3 py-2 rounded border border-gray-300 dark:border-gray-700 dark:bg-slate-800 focus:ring focus:ring-blue-500 outline-none"
                    placeholder="E.g., What are the elements of adverse possession in Texas?"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                  />
                </FormField>
              </div>
              <FormField label="Jurisdiction">
                <input
                   className="w-full px-3 py-2 rounded border border-gray-300 dark:border-gray-700 dark:bg-slate-800 focus:ring focus:ring-blue-500 outline-none"
                   placeholder="E.g., Texas, Ninth Circuit, Federal"
                   value={jurisdiction}
                   onChange={(e) => setJurisdiction(e.target.value)}
                />
              </FormField>
              <FormField label="Source Scope">
                 <select
                   className="w-full px-3 py-2 rounded border border-gray-300 dark:border-gray-700 dark:bg-slate-800 focus:ring focus:ring-blue-500 outline-none"
                   value={scope}
                   onChange={(e) => setScope(e.target.value)}
                 >
                   <option value="federal">Federal</option>
                   <option value="state">State</option>
                   <option value="both">Both</option>
                 </select>
              </FormField>
            </div>
            <BaseDivider />
            <div className="flex justify-start">
              <BaseButton
                type="submit"
                color="info"
                icon={mdiMagnify}
                label={loading ? 'Searching...' : 'Search Case Law'}
                disabled={loading}
              />
            </div>
          </form>
        </CardBox>

        {loading && (
             <CardBox>
                 <div className="text-center py-10">
                    <p className="text-lg animate-pulse">Analyzing legal sources...</p>
                 </div>
             </CardBox>
        )}

        {error && (
            <CardBox className="bg-red-50 text-red-600">
                {error}
            </CardBox>
        )}

        {results && (
            <div className="space-y-4">
                <h3 className="text-xl font-bold ml-1">Search Results</h3>
                {results.length === 0 && <p className="ml-1">No results found.</p>}
                {results.map((res, idx) => (
                    <CardBox key={idx} className="border-l-4 border-blue-500">
                        <div className="flex flex-col gap-2">
                            <div className="flex justify-between items-start">
                                <span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2.5 py-0.5 rounded">
                                    Relevance: {res.relevance_score}%
                                </span>
                            </div>
                            <p className="font-mono text-sm text-gray-500 whitespace-pre-wrap">{res.snippet}</p>
                            {res.rule_statement && (
                                <div className="mt-2 bg-gray-50 dark:bg-slate-800 p-3 rounded">
                                    <span className="font-semibold text-xs uppercase tracking-wide text-gray-500">Rule of Law</span>
                                    <p className="mt-1 italic">{res.rule_statement}</p>
                                </div>
                            )}
                        </div>
                    </CardBox>
                ))}
            </div>
        )}
      </SectionMain>
    </>
  )
}

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

export default AdvancedLegalResearch