'use client'

import { useState } from 'react'
import { canAccessLeadBackup } from '@/lib/auth/roles'
import type { AppUser, LeadRecord, Prospect, OutreachConfig, ExportState } from '@/lib/types'
import { exportLeadsCSV, exportOutreachCSV, downloadCSV } from '@/lib/export/csvExport'
import { exportBulkHTMLTemplate } from '@/lib/export/htmlExport'
import LeadBackupPanel from '@/components/leads/LeadBackupPanel'

interface ExportCenterProps {
  prospects: Prospect[]
  visibleLeads: LeadRecord[]
  config: OutreachConfig
  currentUser: AppUser
  onLibraryReload: () => Promise<void> | void
}

export default function ExportCenter({
  prospects,
  visibleLeads,
  config,
  currentUser,
  onLibraryReload,
}: ExportCenterProps) {
  const [leadsState, setLeadsState] = useState<ExportState>('export_ready')
  const [outreachState, setOutreachState] = useState<ExportState>('export_ready')
  const [htmlState, setHtmlState] = useState<ExportState>('export_ready')
  const [showBackupPanel, setShowBackupPanel] = useState(false)

  const handleExportLeads = async () => {
    if (prospects.length === 0) return
    setLeadsState('exporting')
    try {
      await new Promise(r => setTimeout(r, 300))
      const csv = exportLeadsCSV(prospects)
      downloadCSV(csv, `mspacez-leads-${new Date().toISOString().slice(0, 10)}.csv`)
      setLeadsState('export_success')
      setTimeout(() => setLeadsState('export_ready'), 3000)
    } catch {
      setLeadsState('export_error')
      setTimeout(() => setLeadsState('export_ready'), 3000)
    }
  }

  const handleExportOutreach = async () => {
    if (prospects.length === 0) return
    setOutreachState('exporting')
    try {
      await new Promise(r => setTimeout(r, 500))
      const csv = exportOutreachCSV(prospects, config)
      downloadCSV(csv, `mspacez-outreach-${new Date().toISOString().slice(0, 10)}.csv`)
      setOutreachState('export_success')
      setTimeout(() => setOutreachState('export_ready'), 3000)
    } catch {
      setOutreachState('export_error')
      setTimeout(() => setOutreachState('export_ready'), 3000)
    }
  }

  const handleExportHtml = async () => {
    setHtmlState('exporting')
    try {
      await new Promise(r => setTimeout(r, 200))
      exportBulkHTMLTemplate(config)
      setHtmlState('export_success')
      setTimeout(() => setHtmlState('export_ready'), 3000)
    } catch {
      setHtmlState('export_error')
      setTimeout(() => setHtmlState('export_ready'), 3000)
    }
  }

  const canOpenBackup = canAccessLeadBackup(currentUser)
  const searchLive = prospects.filter(prospect => prospect.acquisition_mode === 'real').length
  const searchDemo = prospects.filter(prospect => prospect.acquisition_mode === 'demo').length
  const searchReady = prospects.filter(prospect => prospect.score >= 50 && (prospect.email || prospect.phone)).length
  const libraryDue = visibleLeads.filter(lead => lead.next_follow_up_at && new Date(lead.next_follow_up_at).getTime() <= Date.now()).length
  const libraryActive = visibleLeads.filter(lead => Boolean(lead.last_contact_at)).length
  const libraryShared = visibleLeads.filter(lead => lead.visibility_scope === 'shared').length

  const ExportCard = ({
    icon, title, description, state, onClick, disabled,
  }: {
    icon: string; title: string; description: string;
    state: ExportState; onClick: () => void; disabled?: boolean
  }) => {
    const isSuccess = state === 'export_success'
    const isError = state === 'export_error'
    const isExporting = state === 'exporting'

    return (
      <button
        onClick={onClick}
        disabled={disabled || isExporting}
        className={`w-full group p-5 bg-[#222a3d] rounded-xl border transition-all text-left ${
          isSuccess ? 'border-[#22c55e]/30 bg-[#22c55e]/5' :
          isError ? 'border-red-500/30 bg-red-500/5' :
          disabled ? 'opacity-40 cursor-not-allowed border-transparent' :
          'border-transparent hover:bg-[#fb7185]/5 hover:border-[#fb7185]/30 active:scale-[0.99]'
        }`}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${
              isSuccess ? 'bg-[#22c55e]/20 text-[#22c55e]' :
              isError ? 'bg-red-500/20 text-red-400' :
              'bg-[#2d3449] text-[#fb7185]'
            }`}>
              <span className="material-symbols-outlined text-xl">
                {isSuccess ? 'check_circle' : isError ? 'error' : icon}
              </span>
            </div>
            <div>
              <p className="text-sm font-bold text-white">{title}</p>
              <p className="text-[11px] text-slate-400 mt-0.5">
                {isSuccess ? 'Export complete!' : isError ? 'Export failed. Try again.' : description}
              </p>
            </div>
          </div>
          <span className={`material-symbols-outlined ${
            isSuccess ? 'text-[#22c55e]' : isError ? 'text-red-400' : isExporting ? 'text-[#ffb95f] animate-spin' : 'text-slate-400 group-hover:text-[#fb7185]'
          } transition-colors`}>
            {isExporting ? 'refresh' : isSuccess ? 'check' : 'download'}
          </span>
        </div>
      </button>
      )
  }

  return (
    <div className="flex h-full overflow-hidden">
      <section className="w-80 bg-[#0b1326] border-r border-[#574143]/10 p-8 overflow-y-auto flex-shrink-0">
        <h3 className="text-lg font-bold text-white mb-6" style={{ fontFamily: 'Manrope, sans-serif' }}>Export Summary</h3>

        <div className="grid grid-cols-2 gap-3 mb-8">
          {[
            { label: 'Search Results', value: prospects.length, color: 'text-white' },
            { label: 'Live Results', value: searchLive, color: 'text-[#22c55e]' },
            { label: 'Demo Fallback', value: searchDemo, color: 'text-[#60a5fa]' },
            { label: 'Ready Now', value: searchReady, color: 'text-[#ffb2b9]' },
            { label: 'Library Leads', value: visibleLeads.length, color: 'text-[#dae2fd]' },
            { label: 'Follow-up Due', value: libraryDue, color: 'text-[#fca5a5]' },
          ].map(s => (
            <div key={s.label} className="bg-[#131b2e] p-4 rounded-xl">
              <p className="text-[9px] font-black text-slate-500 uppercase tracking-widest mb-1">{s.label}</p>
              <p className={`text-2xl font-black ${s.color}`}>{s.value}</p>
            </div>
          ))}
        </div>

        <div className="space-y-4">
          <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-4">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Search Session</p>
            <p className="mt-2 text-xs leading-relaxed text-slate-400">
              Use CSV and outreach exports for the current search result set only. These files are operational outputs, not system backups.
            </p>
          </div>

          <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-4">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Shared Library</p>
            <div className="mt-3 space-y-2 text-xs text-slate-400">
              <div className="flex items-center justify-between">
                <span>Active outreach</span>
                <span className="font-black text-[#93c5fd]">{libraryActive}</span>
              </div>
              <div className="flex items-center justify-between">
                <span>Shared visibility</span>
                <span className="font-black text-[#dae2fd]">{libraryShared}</span>
              </div>
              <div className="flex items-center justify-between">
                <span>Private visibility</span>
                <span className="font-black text-slate-300">{Math.max(0, visibleLeads.length - libraryShared)}</span>
              </div>
            </div>
          </div>

          <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-4">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Backup Policy</p>
            <p className="mt-2 text-xs leading-relaxed text-slate-400">
              JSON is the only survivability format for the shared lead system. CSV remains reporting-only and should not be used for restore.
            </p>
            {!canOpenBackup && (
              <p className="mt-3 text-[11px] text-slate-500">
                Full backup and import controls are restricted to super admin and admin roles.
              </p>
            )}
          </div>
        </div>
      </section>

      <section className="flex-1 p-10 overflow-y-auto">
        <div className="max-w-4xl mx-auto">
          <h2 className="text-2xl font-extrabold text-white tracking-tight mb-2" style={{ fontFamily: 'Manrope, sans-serif' }}>
            Export Center
          </h2>
          <p className="text-slate-400 text-sm mb-8">
            Export current search results for action, and use admin-only JSON backup tools for full library survivability.
          </p>

          <div className="grid gap-6 xl:grid-cols-[1.15fr,0.85fr]">
            <div className="space-y-6">
              <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-5">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Search Session Exports</p>
                    <h3 className="mt-1 text-lg font-extrabold text-slate-100">Operational files for the current result set</h3>
                    <p className="mt-1 text-xs leading-relaxed text-slate-400">
                      These exports are generated from the current search session only. They help the team act on results quickly, but they do not replace shared-library backup.
                    </p>
                  </div>
                  <span className="rounded-full border border-[#22c55e]/20 bg-[#22c55e]/10 px-3 py-1 text-[10px] font-black uppercase tracking-widest text-[#9fe8c4]">
                    {prospects.length} rows
                  </span>
                </div>

                {prospects.length === 0 && (
                  <div className="mt-4 rounded-xl border border-[#574143]/10 bg-[#060e20] p-6 text-center">
                    <span className="material-symbols-outlined text-4xl text-slate-700 mb-3 block">inventory_2</span>
                    <p className="text-sm text-slate-500">Run a search or URL ingestion first to generate operational export files.</p>
                  </div>
                )}

                <div className="mt-4 space-y-3">
                  <ExportCard
                    icon="description"
                    title="CSV Spreadsheet"
                    description={`${prospects.length} leads · flat search result export with scoring, source labels, and branch suggestions`}
                    state={leadsState}
                    onClick={handleExportLeads}
                    disabled={prospects.length === 0}
                  />
                  <ExportCard
                    icon="table_view"
                    title="Outreach CSV"
                    description={`${prospects.length} leads · includes short and full outreach variants in the selected language`}
                    state={outreachState}
                    onClick={handleExportOutreach}
                    disabled={prospects.length === 0}
                  />
                  <ExportCard
                    icon="html"
                    title="HTML Email Template"
                    description="Reusable HTML with personalization tokens for your outreach stack"
                    state={htmlState}
                    onClick={handleExportHtml}
                  />
                </div>
              </div>

              <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-5">
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Search CSV Fields</p>
                <div className="mt-3 flex flex-wrap gap-2">
                  {[
                    'business_name', 'normalized_category', 'phone', 'email', 'website',
                    'address', 'city', 'source', 'source_url', 'score', 'lead_tag',
                    'presence_status', 'suggested_branch', 'offer_type',
                  ].map(field => (
                    <span key={field} className="rounded-lg bg-[#060e20] px-2 py-1 font-mono text-[10px] text-slate-400">
                      {field}
                    </span>
                  ))}
                </div>
              </div>
            </div>

            <div className="space-y-6">
              <div className="rounded-2xl border border-[#574143]/10 bg-[#131b2e] p-5">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-[10px] font-black uppercase tracking-widest text-slate-500">Shared Library Survivability</p>
                    <h3 className="mt-1 text-lg font-extrabold text-slate-100">Full backup and restore for the live lead system</h3>
                    <p className="mt-1 text-xs leading-relaxed text-slate-400">
                      This workflow operates on the saved library, not the transient search session. JSON preserves the full lead payload and CSV stays reporting-only.
                    </p>
                  </div>
                  <span className="rounded-full border border-[#dae2fd]/20 bg-[#dae2fd]/10 px-3 py-1 text-[10px] font-black uppercase tracking-widest text-[#dae2fd]">
                    {visibleLeads.length} visible
                  </span>
                </div>

                <div className="mt-4 space-y-3">
                  <div className="rounded-xl border border-[#574143]/10 bg-[#060e20] p-4">
                    <p className="text-sm font-bold text-slate-200">JSON Backup</p>
                    <p className="mt-1 text-xs leading-relaxed text-slate-400">
                      Full-system survivability format with `full_data`, ownership, assignments, follow-up dates, and operational metadata preserved for import.
                    </p>
                  </div>
                  <div className="rounded-xl border border-[#574143]/10 bg-[#060e20] p-4">
                    <p className="text-sm font-bold text-slate-200">CSV Report</p>
                    <p className="mt-1 text-xs leading-relaxed text-slate-400">
                      Flat reporting export for spreadsheet review only. It is intentionally not a restore format.
                    </p>
                  </div>
                </div>

                {canOpenBackup ? (
                  <button
                    type="button"
                    onClick={() => setShowBackupPanel(prev => !prev)}
                    className={`mt-4 rounded-xl px-4 py-3 text-sm font-black transition ${
                      showBackupPanel
                        ? 'bg-[#dae2fd] text-[#0b1326]'
                        : 'bg-[#0b1326] text-slate-200 hover:text-white'
                    }`}
                  >
                    {showBackupPanel ? 'Hide Backup & Restore' : 'Open Backup & Restore'}
                  </button>
                ) : (
                  <div className="mt-4 rounded-xl border border-[#574143]/10 bg-[#0b1326] px-4 py-3 text-xs leading-relaxed text-slate-500">
                    Backup and import actions are restricted to super admin and admin roles.
                  </div>
                )}
              </div>

              {showBackupPanel && canOpenBackup && (
                <LeadBackupPanel
                  onImported={onLibraryReload}
                  onClose={() => setShowBackupPanel(false)}
                />
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  )
}
