import React, { useState, useEffect, useRef } from 'react';
import { axiosInstance } from '../../services/axios';
import { FileText, Upload, CheckCircle, AlertTriangle, ArrowRight, Eye, RefreshCw } from 'lucide-react';
import PageHeader from '../../components/ui/PageHeader';
import Button from '../../components/ui/Button';
import { useToast } from '../../hooks/use-toast';
import { PageLayout } from '../../components/layout/PageLayout';

interface LegalDoc {
  id: string;
  type: 'NDA' | 'MSA';
  version: string;
  content: string;
  pdfUrl: string | null;
  isActive: boolean;
  createdAt: string;
}

export const LegalTemplatesPage: React.FC = () => {
  const { success, error: toastError } = useToast();
  const [activeTab, setActiveTab] = useState<'NDA' | 'MSA'>('NDA');
  const [ndaDoc, setNdaDoc] = useState<LegalDoc | null>(null);
  const [msaDoc, setMsaDoc] = useState<LegalDoc | null>(null);
  const [loading, setLoading] = useState(true);

  // Form states
  const [version, setVersion] = useState('');
  const [content, setContent] = useState('');
  const [pdfFile, setPdfFile] = useState<File | null>(null);
  const [uploadingPdf, setUploadingPdf] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const fetchActiveDocuments = async () => {
    try {
      setLoading(true);
      const [ndaRes, msaRes] = await Promise.all([
        axiosInstance.get('/legal/documents/active/NDA').catch(() => null),
        axiosInstance.get('/legal/documents/active/MSA').catch(() => null)
      ]);

      setNdaDoc(ndaRes?.data || null);
      setMsaDoc(msaRes?.data || null);

      // Populate defaults for form based on active selection
      const activeDoc = activeTab === 'NDA' ? ndaRes?.data : msaRes?.data;
      if (activeDoc) {
        setVersion(getNextVersion(activeDoc.version));
        setContent(activeDoc.content);
      } else {
        setVersion('1.0');
        setContent('');
      }
    } catch (err) {
      console.error('Failed to load active legal templates:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchActiveDocuments();
  }, [activeTab]);

  const getNextVersion = (current: string) => {
    const num = parseFloat(current);
    if (isNaN(num)) return '1.0';
    return (num + 0.1).toFixed(1);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setPdfFile(e.target.files[0]);
    }
  };

  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!version || !content) {
      toastError('Validation error', 'Please fill in both the version and textual content.');
      return;
    }

    try {
      setSubmitting(true);
      let uploadedUrl: string | null = null;

      // 1. Upload PDF if selected
      if (pdfFile) {
        setUploadingPdf(true);
        const formData = new FormData();
        formData.append('file', pdfFile);
        formData.append('title', `${activeTab} Agreement Template v${version}`);

        const assetRes = await axiosInstance.post('/assets/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        uploadedUrl = assetRes.data.url;
        setUploadingPdf(false);
      }

      // 2. Save New Document Version
      await axiosInstance.post('/legal/documents', {
        type: activeTab,
        version,
        content,
        pdfUrl: uploadedUrl
      });

      success(`Successfully published ${activeTab} version ${version}!`, 'The new legal template version is now active.');
      setPdfFile(null);
      if (fileInputRef.current) fileInputRef.current.value = '';

      await fetchActiveDocuments();
    } catch (err: any) {
      console.error('Failed to publish legal document template:', err);
      toastError('Failed to publish template', err.response?.data?.error || 'Failed to publish legal template.');
    } finally {
      setSubmitting(false);
      setUploadingPdf(false);
    }
  };

  const currentDoc = activeTab === 'NDA' ? ndaDoc : msaDoc;
  const fileHost = (import.meta.env.VITE_API_URL || '/api/v1').replace('/api/v1', '');

  // Header component
  const headerNode = (
    <PageHeader
      title="Legal Agreements"
      subtitle="Configure active documents required during partner onboarding."
    // badge={
    //   <div className="flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-ink-100 border border-ink-200 text-[10px] font-bold text-ink-900 tracking-wider uppercase shrink-0">
    //     <Shield className="w-3.5 h-3.5 text-ink-900" />
    //     <span>Compliance Panel</span>
    //   </div>
    // }
    />
  );

  // Toolbar component
  const toolbarNode = (
    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3.5 p-3.5 bg-ink-0 border border-ink-200 rounded-xl shadow-sm">
      <div className="flex items-center gap-2 flex-1">
        <div className="inline-flex p-1 rounded-lg bg-ink-50 border border-ink-200 shrink-0">
          <button
            onClick={() => setActiveTab('NDA')}
            className={`px-3 py-1.5 rounded-md text-xs font-bold transition-all cursor-pointer ${activeTab === 'NDA' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500 hover:text-ink-900'}`}
          >
            Non-Disclosure (NDA)
          </button>
          <button
            onClick={() => setActiveTab('MSA')}
            className={`px-3 py-1.5 rounded-md text-xs font-bold transition-all cursor-pointer ${activeTab === 'MSA' ? 'bg-ink-0 text-ink-900 shadow-sm' : 'text-ink-500 hover:text-ink-900'}`}
          >
            Master Services (MSA)
          </button>
        </div>
      </div>
    </div>
  );

  return (
    <PageLayout header={headerNode} toolbar={toolbarNode}>
      <div className="p-5 grid grid-cols-1 lg:grid-cols-3 gap-6 flex-1 min-h-0 overflow-y-auto">
        {/* Left Side: Active Status Details */}
        <div className="lg:col-span-1 flex flex-col gap-6">
          <div className="p-4 bg-ink-0 border border-ink-200 shadow-sm rounded-xl">
            <h2 className="text-base font-bold text-ink-900 mb-4">Active Configuration</h2>

            {loading ? (
              <div className="flex flex-col items-center justify-center py-12">
                <RefreshCw className="w-6 h-6 text-ink-400 animate-spin mb-3" />
                <span className="text-xs font-bold text-ink-400">Loading document state...</span>
              </div>
            ) : currentDoc ? (
              <div className="space-y-4">
                <div className="flex items-center justify-between p-3 rounded-lg bg-ink-50 border border-ink-100">
                  <div>
                    <p className="text-xs font-semibold text-ink-400 uppercase tracking-wider">Version</p>
                    <p className="text-base font-extrabold text-ink-900">v{currentDoc.version}</p>
                  </div>
                  <span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-bold bg-ink-900 text-ink-0 border border-ink-700 shadow-sm">
                    <CheckCircle className="w-3.5 h-3.5" />
                    Active
                  </span>
                </div>

                <div>
                  <p className="text-xs font-semibold text-ink-400 uppercase tracking-wider mb-2">Display Mode</p>
                  {currentDoc.pdfUrl ? (
                    <div className="flex items-center gap-2 text-xs font-semibold text-ink-900">
                      <FileText className="w-4 h-4" />
                      <span>Custom PDF Viewer Active</span>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 text-xs font-semibold text-ink-500">
                      <Eye className="w-4 h-4" />
                      <span>Text fallback mode active</span>
                    </div>
                  )}
                </div>

                {currentDoc.pdfUrl && (
                  <div className="pt-2">
                    <p className="text-xs font-semibold text-ink-400 uppercase tracking-wider mb-2">File Source</p>
                    <a
                      href={`${fileHost}${currentDoc.pdfUrl}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-between justify-between p-2 rounded-lg border border-dashed border-ink-200 hover:bg-ink-50 hover:border-ink-400 transition-all text-xs font-bold text-ink-700"
                    >
                      <span className="truncate max-w-[150px]">{currentDoc.pdfUrl.split('/').pop()}</span>
                      <ArrowRight className="w-3.5 h-3.5" />
                    </a>
                  </div>
                )}

                <div className="pt-4 border-t border-ink-100">
                  <p className="text-xs font-semibold text-ink-400 uppercase tracking-wider mb-2">Text Content Sample</p>
                  <p className="text-xs text-ink-500 font-mono leading-relaxed line-clamp-4 bg-ink-50 p-2.5 rounded-lg border border-ink-100">
                    {currentDoc.content}
                  </p>
                </div>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center text-center py-8">
                <AlertTriangle className="w-8 h-8 text-ink-500 mb-2" />
                <p className="text-sm font-bold text-ink-900">No Document Configured</p>
                <p className="text-xs text-ink-500 mt-1">Configure and publish a version to enable partner signatures.</p>
              </div>
            )}
          </div>
        </div>

        {/* Right Side: Publish New Revision form */}
        <div className="lg:col-span-2">
          <form onSubmit={handleFormSubmit} className="p-4 md:p-5 bg-ink-0 border border-ink-200 shadow-sm rounded-xl flex flex-col gap-4">
            <div>
              <h2 className="text-base font-bold text-ink-900">Publish New Revision</h2>
              <p className="text-xs text-ink-500 mt-1">
                Saving a new template automatically deactivates the current active version.
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="md:col-span-1">
                <label className="block text-xs font-semibold text-ink-500 mb-2 uppercase tracking-wider">Version String</label>
                <input
                  type="text"
                  placeholder="e.g. 1.1"
                  value={version}
                  onChange={(e) => setVersion(e.target.value)}
                  className="w-full px-3 py-2 bg-ink-50 border border-ink-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 shadow-sm font-semibold"
                  required
                />
              </div>

              <div className="md:col-span-3">
                <label className="block text-xs font-semibold text-ink-500 mb-2 uppercase tracking-wider">PDF Template (Optional)</label>
                <div
                  onClick={() => fileInputRef.current?.click()}
                  className="flex items-center gap-3 p-2 rounded-lg border border-dashed border-ink-200 hover:border-ink-400 cursor-pointer bg-ink-50 hover:bg-ink-100/50 transition-colors"
                >
                  <div className="w-8 h-8 rounded-lg bg-ink-0 border border-ink-200 flex items-center justify-center text-ink-500">
                    <Upload className="w-4 h-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-bold text-ink-700 truncate">
                      {pdfFile ? pdfFile.name : 'Select custom PDF document'}
                    </p>
                    <p className="text-[10px] text-ink-500 font-medium">Click to select file</p>
                  </div>
                  <input
                    type="file"
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    accept=".pdf"
                    className="hidden"
                  />
                </div>
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-ink-500 mb-2 uppercase tracking-wider">Text Content Fallback</label>
              <textarea
                rows={6}
                placeholder="Insert standard text content here..."
                value={content}
                onChange={(e) => setContent(e.target.value)}
                className="w-full px-3 py-2 bg-ink-50 border border-ink-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 font-mono text-xs leading-relaxed shadow-sm"
                required
              />
              <p className="text-[10px] text-ink-500 font-medium mt-1.5">
                This content will display to partners if no custom PDF has been uploaded.
              </p>
            </div>

            <div className="flex justify-end gap-3 pt-3 border-t border-ink-100">
              <Button
                type="submit"
                disabled={submitting || uploadingPdf}
                variant="primary"
                size="sm"
                icon={<CheckCircle className="w-4 h-4" />}
              >
                {uploadingPdf ? 'Uploading PDF...' : submitting ? 'Publishing...' : 'Publish Template'}
              </Button>
            </div>
          </form>
        </div>
      </div>
    </PageLayout>
  );
};

export default LegalTemplatesPage;
