import { useEffect, useState } from 'react'
import { Card } from '@/components/ui/Card'
import { Button } from '@/components/ui/Button'
import { Skeleton } from '@/components/ui/Skeleton'
import { Badge } from '@/components/ui/Badge'
import { formatCurrency, formatDate } from '@/lib/utils'
import {
  FileText,
  Plus,
  Search,
  MoreHorizontal,
  CheckCircle2,
  Clock,
  AlertTriangle,
  Download,
  Eye,
  Copy,
  Shield,
  Briefcase,
  Globe,
} from 'lucide-react'

interface Contract {
  id: string
  template_type: string
  name: string
  counterparty: string
  counterparty_org?: string
  status: string
  value?: number
  currency?: string
  start_date?: string
  end_date?: string
  renewal_date?: string
  responsible?: string
  created_at: string
}

interface ContractTemplate {
  id: string
  type: string
  name: string
  description: string
  category: string
  product_module?: string
  version: string
  status: string
  language: string
  jurisdiction: string
  sections: {
    id: string
    title: string
    order: number
    required: boolean
    content: string
    variables?: string[]
  }[]
  default_terms: {
    payment_terms: string
    currency: string
    vat_rate: number
    contract_period: string
    notice_period: string
    auto_renewal: boolean
    sla_enabled: boolean
    sla_uptime: number
    data_processing: boolean
    data_location: string
    support_level: string
  }
}

interface ProductLink {
  product_id: string
  product_name: string
  product_type: string
  required_contracts: string[]
  optional_contracts: string[]
}

const statusColors: Record<string, any> = {
  draft: { variant: 'default', icon: Clock },
  pending_signature: { variant: 'warning', icon: Clock },
  active: { variant: 'success', icon: CheckCircle2 },
  expired: { variant: 'danger', icon: AlertTriangle },
  terminated: { variant: 'default', icon: AlertTriangle },
  disputed: { variant: 'danger', icon: AlertTriangle },
}

const categoryColors: Record<string, string> = {
  aamos: 'primary',
  quixzoom: 'success',
  legal: 'warning',
  hr: 'default',
}

export function LegalPage() {
  const [activeTab, setActiveTab] = useState('contracts')
  const [searchQuery, setSearchQuery] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  const [contracts, setContracts] = useState<Contract[]>([])
  const [templates, setTemplates] = useState<ContractTemplate[]>([])
  const [productLinks, setProductLinks] = useState<ProductLink[]>([])
  const [selectedTemplate, setSelectedTemplate] = useState<ContractTemplate | null>(null)
  const [showTemplateModal, setShowTemplateModal] = useState(false)

  useEffect(() => {
    async function fetchData() {
      setLoading(true)
      setError('')
      try {
        const [contractsRes, templatesRes, linksRes] = await Promise.all([
          fetch('/api/v1/legal/contracts').then(r => r.json()),
          fetch('/api/v1/legal/templates').then(r => r.json()),
          fetch('/api/v1/legal/product-links').then(r => r.json()),
        ])
        setContracts(contractsRes.contracts || [])
        setTemplates(templatesRes.templates || [])
        setProductLinks(linksRes.links || [])
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load legal data')
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  const filteredContracts = contracts.filter(
    (c) =>
      c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.counterparty.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.template_type.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const filteredTemplates = templates.filter(
    (t) =>
      t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.category.toLowerCase().includes(searchQuery.toLowerCase())
  )

  if (loading) {
    return (
      <div className="space-y-8">
        <div className="grid grid-cols-1 sm:grid-cols-4 gap-5">
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
          <Skeleton className="h-[80px]" />
        </div>
        <Skeleton className="h-[400px]" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-danger">{error}</p>
      </div>
    )
  }

  const tabs = [
    { id: 'contracts', label: 'Avtal', icon: FileText },
    { id: 'templates', label: 'Mallar', icon: Copy },
    { id: 'products', label: 'Produktkopplingar', icon: Briefcase },
  ]

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold text-text-primary">Legal</h1>
          <p className="text-sm text-text-secondary mt-0.5">Avtal, mallar och produktkopplingar</p>
        </div>
        <Button icon={<Plus size={16} />}>Nytt avtal</Button>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-5">
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
              <FileText size={20} />
            </div>
            <div>
              <p className="text-2xl font-semibold">{contracts.length}</p>
              <p className="text-xs text-text-secondary">Totalt avtal</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-success/10 text-success flex items-center justify-center">
              <CheckCircle2 size={20} />
            </div>
            <div>
              <p className="text-2xl font-semibold">
                {contracts.filter(c => c.status === 'active').length}
              </p>
              <p className="text-xs text-text-secondary">Aktiva</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-warning/10 text-warning flex items-center justify-center">
              <Clock size={20} />
            </div>
            <div>
              <p className="text-2xl font-semibold">
                {contracts.filter(c => c.status === 'pending_signature').length}
              </p>
              <p className="text-xs text-text-secondary">Väntar signering</p>
            </div>
          </div>
        </Card>
        <Card padding="md">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-danger/10 text-danger flex items-center justify-center">
              <AlertTriangle size={20} />
            </div>
            <div>
              <p className="text-2xl font-semibold">
                {contracts.filter(c => c.status === 'expired' || c.status === 'terminated').length}
              </p>
              <p className="text-xs text-text-secondary">Utgångna</p>
            </div>
          </div>
        </Card>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1 bg-bg rounded-xl p-1 overflow-x-auto">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors whitespace-nowrap flex items-center gap-2 ${
              activeTab === tab.id
                ? 'bg-surface text-text-primary shadow-sm'
                : 'text-text-secondary hover:text-text-primary'
            }`}
          >
            <tab.icon size={16} />
            {tab.label}
          </button>
        ))}
      </div>

      {/* Search */}
      <div className="relative">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" />
        <input
          type="text"
          placeholder="Sök avtal, mallar eller produkter..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="w-full h-10 pl-9 pr-4 rounded-[14px] border bg-surface text-sm"
        />
      </div>

      {/* Contracts Tab */}
      {activeTab === 'contracts' && (
        <Card>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Avtal</th>
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Motpart</th>
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Typ</th>
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Status</th>
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Värde</th>
                  <th className="text-left text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3">Period</th>
                  <th className="text-right text-xs font-medium text-text-secondary uppercase tracking-wider px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filteredContracts.map((contract) => {
                  const statusConfig = statusColors[contract.status] || statusColors.draft
                  return (
                    <tr key={contract.id} className="hover:bg-bg transition-colors">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
                            <FileText size={14} />
                          </div>
                          <div>
                            <p className="text-sm font-medium text-text-primary">{contract.name}</p>
                            <p className="text-xs text-text-secondary">{contract.template_type}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <p className="text-sm text-text-primary">{contract.counterparty}</p>
                        {contract.counterparty_org && (
                          <p className="text-xs text-text-secondary">{contract.counterparty_org}</p>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant="default" className="text-xs">
                          {contract.template_type}
                        </Badge>
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant={statusConfig.variant as any} className="text-xs flex items-center gap-1">
                          <statusConfig.icon size={12} />
                          {contract.status}
                        </Badge>
                      </td>
                      <td className="px-4 py-3">
                        {contract.value ? (
                          <p className="text-sm font-medium">{formatCurrency(contract.value)} {contract.currency}</p>
                        ) : (
                          <p className="text-sm text-text-secondary">—</p>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <p className="text-sm text-text-secondary">
                          {contract.start_date ? formatDate(contract.start_date) : '—'}
                          {contract.end_date && ` → ${formatDate(contract.end_date)}`}
                        </p>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                            <Eye size={14} />
                          </button>
                          <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                            <Download size={14} />
                          </button>
                          <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary">
                            <MoreHorizontal size={14} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })}
                {filteredContracts.length === 0 && (
                  <tr>
                    <td colSpan={7} className="text-center text-text-secondary py-8">
                      Inga avtal hittades
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {/* Templates Tab */}
      {activeTab === 'templates' && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredTemplates.map((template) => (
            <div
              key={template.id}
              className="cursor-pointer hover:border-primary transition-colors"
              onClick={() => {
                setSelectedTemplate(template)
                setShowTemplateModal(true)
              }}
            >
            <Card>
              <div className="p-4">
                <div className="flex items-start justify-between mb-3">
                  <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
                    <FileText size={20} />
                  </div>
                  <Badge variant={categoryColors[template.category] as any} className="text-xs">
                    {template.category}
                  </Badge>
                </div>
                <h3 className="font-semibold text-text-primary mb-1">{template.name}</h3>
                <p className="text-sm text-text-secondary mb-3">{template.description}</p>
                <div className="flex items-center gap-2 text-xs text-text-tertiary">
                  <Globe size={12} />
                  {template.jurisdiction}
                  <span className="mx-1">•</span>
                  <Shield size={12} />
                  v{template.version}
                  <span className="mx-1">•</span>
                  {template.sections.length} sektioner
                </div>
              </div>
            </Card>
            </div>
          ))}
          {filteredTemplates.length === 0 && (
            <div className="col-span-full text-center text-text-secondary py-8">
              Inga mallar hittades
            </div>
          )}
        </div>
      )}

      {/* Products Tab */}
      {activeTab === 'products' && (
        <div className="space-y-6">
          {productLinks.map((link) => (
            <Card key={link.product_id}>
              <div className="p-4">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center">
                    <Briefcase size={20} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-text-primary">{link.product_name}</h3>
                    <p className="text-sm text-text-secondary">{link.product_type}</p>
                  </div>
                </div>
                <div className="space-y-3">
                  <div>
                    <p className="text-xs font-medium text-text-secondary uppercase mb-2">Krävs</p>
                    <div className="flex flex-wrap gap-2">
                      {link.required_contracts.map((contract) => (
                        <Badge key={contract} variant="primary" className="text-xs">
                          {contract}
                        </Badge>
                      ))}
                    </div>
                  </div>
                  {link.optional_contracts.length > 0 && (
                    <div>
                      <p className="text-xs font-medium text-text-secondary uppercase mb-2">Valbart</p>
                      <div className="flex flex-wrap gap-2">
                        {link.optional_contracts.map((contract) => (
                          <Badge key={contract} variant="default" className="text-xs">
                            {contract}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* Template Detail Modal */}
      {showTemplateModal && selectedTemplate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <Card>
              <div className="p-6">
                <div className="flex items-start justify-between mb-6">
                  <div>
                    <h2 className="text-xl font-semibold">{selectedTemplate.name}</h2>
                    <p className="text-text-secondary">{selectedTemplate.description}</p>
                  </div>
                  <button
                    onClick={() => setShowTemplateModal(false)}
                    className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-bg text-text-secondary"
                  >
                    ✕
                  </button>
                </div>

                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Kategori</p>
                    <p className="font-medium">{selectedTemplate.category}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Jurisdiktion</p>
                    <p className="font-medium">{selectedTemplate.jurisdiction}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Språk</p>
                    <p className="font-medium">{selectedTemplate.language}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Version</p>
                    <p className="font-medium">{selectedTemplate.version}</p>
                  </div>
                </div>

                <h3 className="font-semibold mb-3">Avtalssektioner</h3>
                <div className="space-y-2 mb-6">
                  {selectedTemplate.sections.map((section) => (
                    <div key={section.id} className="p-3 bg-surface rounded-lg">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-xs text-text-tertiary">{section.order}.</span>
                        <p className="font-medium text-sm">{section.title}</p>
                        {section.required && (
                          <Badge variant="danger" className="text-xs">Krävs</Badge>
                        )}
                      </div>
                      <p className="text-sm text-text-secondary">{section.content}</p>
                      {section.variables && section.variables.length > 0 && (
                        <div className="flex flex-wrap gap-1 mt-2">
                          {section.variables.map((v) => (
                            <code key={v} className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded">
                              {'{{' + v + '}}'}
                            </code>
                          ))}
                        </div>
                      )}
                    </div>
                  ))}
                </div>

                <h3 className="font-semibold mb-3">Standardvillkor</h3>
                <div className="grid grid-cols-2 gap-3 mb-6">
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Betalningsvillkor</p>
                    <p className="text-sm">{selectedTemplate.default_terms.payment_terms}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Valuta</p>
                    <p className="text-sm">{selectedTemplate.default_terms.currency}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Avtalsperiod</p>
                    <p className="text-sm">{selectedTemplate.default_terms.contract_period}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Uppsägningstid</p>
                    <p className="text-sm">{selectedTemplate.default_terms.notice_period}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">Auto-förnyelse</p>
                    <p className="text-sm">{selectedTemplate.default_terms.auto_renewal ? 'Ja' : 'Nej'}</p>
                  </div>
                  <div className="p-3 bg-surface rounded-lg">
                    <p className="text-xs text-text-secondary">SLA</p>
                    <p className="text-sm">
                      {selectedTemplate.default_terms.sla_enabled
                        ? `${selectedTemplate.default_terms.sla_uptime}% uptime`
                        : 'Ej aktiverat'}
                    </p>
                  </div>
                </div>

                <div className="flex gap-3">
                  <Button className="flex-1">
                    <Plus size={16} className="mr-2" />
                    Skapa avtal från mall
                  </Button>
                  <Button variant="secondary">
                    <Download size={16} className="mr-2" />
                    Förhandsgranska
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        </div>
      )}
    </div>
  )
}
