'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import {
  ArrowLeft,
  Edit,
  History,
  Award,
  TrendingDown,
  DollarSign,
  Target,
  Calendar,
  User,
  FileText,
  Clock,
  Loader2,
  Plus,
  Check,
  X,
  Receipt,
  FileSignature
} from 'lucide-react'
import ProtectedRoute from '@/components/ProtectedRoute'
import LoadingSpinner from '@/components/LoadingSpinner'
import Modal from '@/components/Modal'
import { dealsAPI, Deal } from '@/lib/api/deals'
import { quotesAPI, Quote } from '@/lib/api/quotes'
import { costSheetsAPI, CostSheet, CostSheetItem } from '@/lib/api/costSheets'
import { contractsAPI, Contract, CreateContractData } from '@/lib/api/contracts'
import { invoicesAPI, Invoice, InvoiceItem } from '@/lib/api/invoices'
import { useLanguage } from '@/contexts/LanguageContext'

function DealDetailContent() {
  const params = useParams()
  const router = useRouter()
  const dealId = params.id as string
  const { t } = useLanguage()

  const [deal, setDeal] = useState<Deal | null>(null)
  const [quotes, setQuotes] = useState<Quote[]>([])
  const [costSheets, setCostSheets] = useState<CostSheet[]>([])
  const [contracts, setContracts] = useState<Contract[]>([])
  const [invoices, setInvoices] = useState<Invoice[]>([])
  const [history, setHistory] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'info' | 'quotes' | 'costSheets' | 'contracts' | 'invoices' | 'history'>('info')
  const [showWinDialog, setShowWinDialog] = useState(false)
  const [showLoseDialog, setShowLoseDialog] = useState(false)
  const [showCostSheetModal, setShowCostSheetModal] = useState(false)
  const [showContractModal, setShowContractModal] = useState(false)
  const [showInvoiceModal, setShowInvoiceModal] = useState(false)
  const [showPaymentModal, setShowPaymentModal] = useState<Invoice | null>(null)
  const [winData, setWinData] = useState({ actualValue: 0, wonReason: '' })
  const [loseData, setLoseData] = useState({ lostReason: '' })
  const [submitting, setSubmitting] = useState(false)
  const [costSheetForm, setCostSheetForm] = useState({
    items: [{ description: '', source: '', cost: 0, quantity: 1 }] as CostSheetItem[],
    totalCost: 0,
    suggestedPrice: 0,
    profitMargin: 0,
  })
  const [contractForm, setContractForm] = useState<CreateContractData>({
    dealId: '',
    title: '',
    type: 'SALES',
    clientInfo: {},
    companyInfo: {},
    startDate: '',
    endDate: '',
    value: 0,
    paymentTerms: {},
    deliveryTerms: {},
    terms: '',
  })
  const [invoiceForm, setInvoiceForm] = useState({
    items: [{ description: '', quantity: 1, unitPrice: 0, total: 0 }] as InvoiceItem[],
    subtotal: 0,
    taxAmount: 0,
    total: 0,
    dueDate: '',
  })
  const [paymentForm, setPaymentForm] = useState({ paidAmount: 0, paidDate: new Date().toISOString().slice(0, 10) })

  useEffect(() => {
    if (showPaymentModal) {
      setPaymentForm({ paidAmount: Number(showPaymentModal?.total) || 0, paidDate: new Date().toISOString().slice(0, 10) })
    }
  }, [showPaymentModal])

  useEffect(() => {
    if (deal && showContractModal) {
      const contact = deal.contact
      setContractForm((f) => ({
        ...f,
        dealId: deal.id,
        clientInfo: contact ? { name: contact.name, email: contact.email, phone: contact.phone } : {},
        companyInfo: f.companyInfo && Object.keys(f.companyInfo).length ? f.companyInfo : {},
      }))
    }
  }, [deal, showContractModal])

  const handleCreateCostSheet = async () => {
    const items = costSheetForm.items.filter((i) => i.cost > 0 || i.description)
    if (!items.length || costSheetForm.totalCost <= 0 || costSheetForm.suggestedPrice <= 0) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await costSheetsAPI.create({
        dealId,
        items,
        totalCost: costSheetForm.totalCost,
        suggestedPrice: costSheetForm.suggestedPrice,
        profitMargin: costSheetForm.profitMargin,
      })
      toast.success(t('crm.costSheetCreated'))
      setShowCostSheetModal(false)
      setCostSheetForm({ items: [{ description: '', source: '', cost: 0, quantity: 1 }], totalCost: 0, suggestedPrice: 0, profitMargin: 0 })
      fetchCostSheets()
    } catch (e: any) {
      toast.error(e.response?.data?.message || 'Failed')
    } finally {
      setSubmitting(false)
    }
  }

  const handleCreateContract = async () => {
    if (!contractForm.title || !contractForm.startDate || contractForm.value <= 0) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await contractsAPI.create({
        ...contractForm,
        dealId,
        clientInfo: contractForm.clientInfo || {},
        companyInfo: contractForm.companyInfo || {},
        paymentTerms: contractForm.paymentTerms || {},
        deliveryTerms: contractForm.deliveryTerms || {},
      })
      toast.success(t('crm.contractCreated'))
      setShowContractModal(false)
      setContractForm({ dealId: '', title: '', type: 'SALES', clientInfo: {}, companyInfo: {}, startDate: '', endDate: '', value: 0, paymentTerms: {}, deliveryTerms: {}, terms: '' })
      fetchContracts()
    } catch (e: any) {
      toast.error(e.response?.data?.message || 'Failed')
    } finally {
      setSubmitting(false)
    }
  }

  const handleCreateInvoice = async () => {
    const items = invoiceForm.items.filter((i) => i.quantity > 0 && i.unitPrice >= 0)
    if (!items.length || invoiceForm.total <= 0 || !invoiceForm.dueDate) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await invoicesAPI.create({
        dealId,
        items: items.map((i) => ({ ...i, total: (i.quantity || 0) * (i.unitPrice || 0) })),
        subtotal: invoiceForm.subtotal,
        taxAmount: invoiceForm.taxAmount,
        total: invoiceForm.total,
        dueDate: invoiceForm.dueDate,
      })
      toast.success(t('crm.invoiceCreated'))
      setShowInvoiceModal(false)
      setInvoiceForm({ items: [{ description: '', quantity: 1, unitPrice: 0, total: 0 }], subtotal: 0, taxAmount: 0, total: 0, dueDate: '' })
      fetchInvoices()
    } catch (e: any) {
      toast.error(e.response?.data?.message || 'Failed')
    } finally {
      setSubmitting(false)
    }
  }

  const handleRecordPayment = async () => {
    if (!showPaymentModal || paymentForm.paidAmount <= 0) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await invoicesAPI.recordPayment(showPaymentModal.id, paymentForm.paidAmount, paymentForm.paidDate)
      toast.success(t('crm.paymentRecorded'))
      setShowPaymentModal(null)
      setPaymentForm({ paidAmount: 0, paidDate: new Date().toISOString().slice(0, 10) })
      fetchInvoices()
    } catch (e: any) {
      toast.error(e.response?.data?.message || 'Failed')
    } finally {
      setSubmitting(false)
    }
  }

  useEffect(() => {
    fetchDeal()
  }, [dealId])

  useEffect(() => {
    if (deal) {
      fetchQuotes()
      fetchCostSheets()
      fetchContracts()
      fetchInvoices()
      fetchHistory()
    }
  }, [deal])

  const fetchDeal = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await dealsAPI.getById(dealId)
      setDeal(data)
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to load deal'
      setError(message)
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }

  const fetchQuotes = async () => {
    try {
      const data = await quotesAPI.getByDeal(dealId)
      setQuotes(data || [])
    } catch {
      setQuotes([])
    }
  }

  const fetchHistory = async () => {
    try {
      const data = await dealsAPI.getHistory(dealId)
      setHistory(data || [])
    } catch {
      setHistory([])
    }
  }

  const fetchCostSheets = async () => {
    try {
      const data = await costSheetsAPI.getByDeal(dealId)
      setCostSheets(data || [])
    } catch {
      setCostSheets([])
    }
  }

  const fetchContracts = async () => {
    try {
      const data = await contractsAPI.getByDeal(dealId)
      setContracts(data || [])
    } catch {
      setContracts([])
    }
  }

  const fetchInvoices = async () => {
    try {
      const data = await invoicesAPI.getByDeal(dealId)
      setInvoices(data || [])
    } catch {
      setInvoices([])
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      ACTIVE: 'bg-green-100 text-green-700',
      WON: 'bg-blue-100 text-blue-700',
      LOST: 'bg-red-100 text-red-700'
    }
    return colors[status] || 'bg-gray-100 text-gray-700'
  }

  const getStructureLabel = (structure: string) => {
    const labels: Record<string, string> = {
      B2B: 'B2B',
      B2C: 'B2C',
      B2G: 'B2G',
      PARTNERSHIP: 'Partnership'
    }
    return labels[structure] || structure
  }

  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '—'
    return new Date(dateStr).toLocaleDateString()
  }

  const handleWin = async () => {
    if (!deal || !winData.actualValue || !winData.wonReason) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await dealsAPI.win(deal.id, winData.actualValue, winData.wonReason)
      toast.success(t('crm.winSuccess'))
      setShowWinDialog(false)
      setWinData({ actualValue: 0, wonReason: '' })
      fetchDeal()
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to mark as won')
    } finally {
      setSubmitting(false)
    }
  }

  const handleLose = async () => {
    if (!deal || !loseData.lostReason) {
      toast.error(t('crm.fixFormErrors'))
      return
    }
    setSubmitting(true)
    try {
      await dealsAPI.lose(deal.id, loseData.lostReason)
      toast.success(t('crm.loseSuccess'))
      setShowLoseDialog(false)
      setLoseData({ lostReason: '' })
      fetchDeal()
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to mark as lost')
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <LoadingSpinner size="lg" message={t('crm.loadingDeals')} />
      </div>
    )
  }

  if (error || !deal) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-2xl font-bold text-gray-900 mb-2">{error || 'Deal not found'}</p>
          <Link
            href="/crm"
            className="inline-flex items-center gap-2 px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
          >
            <ArrowLeft className="h-4 w-4" />
            {t('common.back')} {t('nav.crm')}
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link
                href="/crm"
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <ArrowLeft className="h-5 w-5 text-gray-600" />
              </Link>
              <div>
                <div className="flex items-center gap-3">
                  <h1 className="text-2xl font-bold text-gray-900">{deal.name}</h1>
                  <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(deal.status)}`}>
                    {deal.status}
                  </span>
                  <span className="px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                    {getStructureLabel(deal.structure)} - {deal.stage}
                  </span>
                </div>
                <p className="text-sm text-gray-600 mt-1">{deal.dealNumber}</p>
              </div>
            </div>

            <div className="flex items-center gap-3">
              {deal.status === 'ACTIVE' && (
                <>
                  <button
                    onClick={() => {
                      setWinData({ actualValue: deal.estimatedValue, wonReason: '' })
                      setShowWinDialog(true)
                    }}
                    className="flex items-center gap-2 px-4 py-2 border border-green-300 text-green-700 rounded-lg hover:bg-green-50"
                  >
                    <Award className="h-4 w-4" />
                    {t('crm.win')}
                  </button>
                  <button
                    onClick={() => {
                      setLoseData({ lostReason: '' })
                      setShowLoseDialog(true)
                    }}
                    className="flex items-center gap-2 px-4 py-2 border border-red-300 text-red-700 rounded-lg hover:bg-red-50"
                  >
                    <TrendingDown className="h-4 w-4" />
                    {t('crm.lose')}
                  </button>
                </>
              )}
              <button
                onClick={() => router.push(`/crm?edit=${dealId}`)}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                <Edit className="h-4 w-4" />
                {t('common.edit')}
              </button>
              <button
                onClick={() => setActiveTab('history')}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                <History className="h-4 w-4" />
                {t('crm.history')}
              </button>
            </div>
          </div>

          <nav className="flex items-center gap-2 text-sm text-gray-600 mt-4">
            <Link href="/dashboard" className="hover:text-green-600">{t('nav.dashboard')}</Link>
            <span>/</span>
            <Link href="/crm" className="hover:text-green-600">{t('nav.crm')}</Link>
            <span>/</span>
            <span className="text-gray-900 font-medium">{deal.name}</span>
          </nav>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-1">
            <div className="bg-white rounded-xl shadow-sm border p-6">
              <div className="text-center mb-6">
                <div className="h-24 w-24 rounded-full bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center text-white text-3xl font-bold mx-auto">
                  {deal.name.charAt(0)}
                </div>
                <h2 className="mt-3 font-semibold text-gray-900">{deal.name}</h2>
                <span className={`inline-block mt-2 px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(deal.status)}`}>
                  {deal.status}
                </span>
              </div>
            </div>
          </div>

          <div className="lg:col-span-2">
            <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
              <div className="border-b border-gray-200">
                <nav className="flex gap-4 px-6 overflow-x-auto">
                  {(['info', 'quotes', 'costSheets', 'contracts', 'invoices', 'history'] as const).map((tab) => (
                    <button
                      key={tab}
                      onClick={() => setActiveTab(tab)}
                      className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap ${
                        activeTab === tab
                          ? 'border-green-600 text-green-600'
                          : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                      }`}
                    >
                      {tab === 'info' ? t('crm.dealInfo') : tab === 'quotes' ? t('crm.quotes') : tab === 'costSheets' ? t('crm.costSheets') : tab === 'contracts' ? t('crm.contracts') : tab === 'invoices' ? t('crm.invoices') : t('crm.history')}
                    </button>
                  ))}
                </nav>
              </div>

              <div className="p-6">
                {activeTab === 'info' && (
                  <div className="space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="flex items-start gap-3">
                        <User className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.contact')}</p>
                          <Link
                            href={`/contacts/${deal.contactId}`}
                            className="font-medium text-green-600 hover:underline"
                          >
                            {deal.contact?.name || '—'}
                          </Link>
                        </div>
                      </div>
                      <div className="flex items-start gap-3">
                        <Target className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.stage')}</p>
                          <p className="font-medium text-gray-900">{deal.stage}</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-3">
                        <DollarSign className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.estimatedValue')}</p>
                          <p className="font-medium text-gray-900">
                            {deal.estimatedValue?.toLocaleString() || 0} SAR
                          </p>
                        </div>
                      </div>
                      <div className="flex items-start gap-3">
                        <Target className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.probability')}</p>
                          <p className="font-medium text-gray-900">{deal.probability || 0}%</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-3">
                        <Calendar className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.expectedCloseDate')}</p>
                          <p className="font-medium text-gray-900">{formatDate(deal.expectedCloseDate)}</p>
                        </div>
                      </div>
                      <div className="flex items-start gap-3">
                        <User className="h-5 w-5 text-gray-400 mt-0.5" />
                        <div>
                          <p className="text-sm text-gray-500">{t('crm.owner')}</p>
                          <p className="font-medium text-gray-900">{deal.owner?.username || deal.owner?.email || '—'}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {activeTab === 'quotes' && (
                  <div>
                    {quotes.length === 0 ? (
                      <div className="text-center py-12 text-gray-500">
                        <FileText className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('common.noData')}</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {quotes.map((q) => (
                          <div
                            key={q.id}
                            className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50"
                          >
                            <div className="flex justify-between items-start">
                              <div>
                                <p className="font-medium text-gray-900">{q.quoteNumber}</p>
                                <p className="text-sm text-gray-500">v{q.version} · {q.status}</p>
                              </div>
                              <p className="font-semibold text-gray-900">{Number(q.total)?.toLocaleString()} SAR</p>
                            </div>
                            <p className="text-xs text-gray-500 mt-2">
                              {formatDate(q.validUntil)} · {formatDate(q.createdAt)}
                            </p>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'costSheets' && (
                  <div>
                    <div className="flex justify-between items-center mb-4">
                      <h3 className="font-semibold text-gray-900">{t('crm.costSheets')}</h3>
                      <button onClick={() => setShowCostSheetModal(true)} className="flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm">
                        <Plus className="h-4 w-4" />
                        {t('crm.addCostSheet')}
                      </button>
                    </div>
                    {costSheets.length === 0 ? (
                      <div className="text-center py-12 text-gray-500">
                        <FileText className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('common.noData')}</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {costSheets.map((cs) => (
                          <div key={cs.id} className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                            <div className="flex justify-between items-start">
                              <div>
                                <p className="font-medium text-gray-900">{cs.costSheetNumber}</p>
                                <p className="text-sm text-gray-500">v{cs.version} · {cs.status}</p>
                                <p className="text-xs text-gray-500 mt-1">
                                  {Number(cs.totalCost)?.toLocaleString()} SAR cost · {Number(cs.suggestedPrice)?.toLocaleString()} SAR suggested · {Number(cs.profitMargin)}% margin
                                </p>
                              </div>
                              {cs.status === 'DRAFT' && (
                                <div className="flex gap-2">
                                  <button onClick={async () => { try { await costSheetsAPI.approve(cs.id); toast.success(t('crm.costSheetApproved')); fetchCostSheets(); } catch (e: any) { toast.error(e.response?.data?.message || 'Failed'); } }} className="flex items-center gap-1 px-2 py-1 text-green-600 border border-green-300 rounded hover:bg-green-50 text-sm">
                                    <Check className="h-4 w-4" />
                                    {t('crm.approve')}
                                  </button>
                                  <button onClick={async () => { try { await costSheetsAPI.reject(cs.id); toast.success(t('crm.costSheetRejected')); fetchCostSheets(); } catch (e: any) { toast.error(e.response?.data?.message || 'Failed'); } }} className="flex items-center gap-1 px-2 py-1 text-red-600 border border-red-300 rounded hover:bg-red-50 text-sm">
                                    <X className="h-4 w-4" />
                                    {t('crm.reject')}
                                  </button>
                                </div>
                              )}
                            </div>
                            <p className="text-xs text-gray-500 mt-2">{formatDate(cs.createdAt)}</p>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'contracts' && (
                  <div>
                    <div className="flex justify-between items-center mb-4">
                      <h3 className="font-semibold text-gray-900">{t('crm.contracts')}</h3>
                      <button onClick={() => setShowContractModal(true)} className="flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm">
                        <Plus className="h-4 w-4" />
                        {t('crm.addContract')}
                      </button>
                    </div>
                    {contracts.length === 0 ? (
                      <div className="text-center py-12 text-gray-500">
                        <FileSignature className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('common.noData')}</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {contracts.map((c) => (
                          <div key={c.id} className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                            <div className="flex justify-between items-start">
                              <div>
                                <p className="font-medium text-gray-900">{c.contractNumber} · {c.title}</p>
                                <p className="text-sm text-gray-500">{c.type} · {c.status}</p>
                                <p className="text-xs text-gray-500 mt-1">
                                  {Number(c.value)?.toLocaleString()} SAR · {formatDate(c.startDate)} {c.endDate ? `– ${formatDate(c.endDate)}` : ''}
                                </p>
                              </div>
                              {c.status === 'PENDING_SIGNATURE' && (
                                <button onClick={async () => { try { await contractsAPI.sign(c.id); toast.success(t('crm.contractSigned')); fetchContracts(); } catch (e: any) { toast.error(e.response?.data?.message || 'Failed'); } }} className="flex items-center gap-1 px-2 py-1 text-green-600 border border-green-300 rounded hover:bg-green-50 text-sm">
                                  <FileSignature className="h-4 w-4" />
                                  {t('crm.markSigned')}
                                </button>
                              )}
                            </div>
                            <p className="text-xs text-gray-500 mt-2">{formatDate(c.createdAt)}</p>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'invoices' && (
                  <div>
                    <div className="flex justify-between items-center mb-4">
                      <h3 className="font-semibold text-gray-900">{t('crm.invoices')}</h3>
                      <button onClick={() => setShowInvoiceModal(true)} className="flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm">
                        <Plus className="h-4 w-4" />
                        {t('crm.addInvoice')}
                      </button>
                    </div>
                    {invoices.length === 0 ? (
                      <div className="text-center py-12 text-gray-500">
                        <Receipt className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('common.noData')}</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {invoices.map((inv) => (
                          <div key={inv.id} className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                            <div className="flex justify-between items-start">
                              <div>
                                <p className="font-medium text-gray-900">{inv.invoiceNumber}</p>
                                <p className="text-sm text-gray-500">{inv.status}</p>
                                <p className="text-xs text-gray-500 mt-1">
                                  {Number(inv.total)?.toLocaleString()} SAR · {inv.paidAmount ? `${Number(inv.paidAmount)?.toLocaleString()} paid` : ''} · due {formatDate(inv.dueDate)}
                                </p>
                              </div>
                              {(inv.status === 'SENT' || inv.status === 'OVERDUE') && (
                                <button onClick={() => setShowPaymentModal(inv)} className="flex items-center gap-1 px-2 py-1 text-green-600 border border-green-300 rounded hover:bg-green-50 text-sm">
                                  <DollarSign className="h-4 w-4" />
                                  {t('crm.recordPayment')}
                                </button>
                              )}
                            </div>
                            <p className="text-xs text-gray-500 mt-2">{formatDate(inv.createdAt)}</p>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'history' && (
                  <div>
                    {history.length === 0 ? (
                      <div className="text-center py-12 text-gray-500">
                        <Clock className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                        <p>{t('common.noData')}</p>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {history.map((h: any, i: number) => (
                          <div key={i} className="flex gap-4 border-b border-gray-100 pb-4 last:border-0">
                            <div className="flex-shrink-0 w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                              <History className="h-5 w-5 text-gray-500" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="font-medium text-gray-900">{h.action}</p>
                              <p className="text-sm text-gray-500">
                                {formatDate(h.createdAt)} · {h.userId || '—'}
                              </p>
                              {h.changes && (
                                <pre className="mt-2 text-xs text-gray-600 overflow-x-auto max-h-24">
                                  {JSON.stringify(h.changes, null, 2)}
                                </pre>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>

      {/* Win Dialog */}
      {showWinDialog && deal && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowWinDialog(false)} />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-green-100 p-3 rounded-full">
                  <Award className="h-6 w-6 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">{t('crm.markDealWon')}</h3>
                  <p className="text-sm text-gray-600">{deal.name}</p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('crm.actualValue')} <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={winData.actualValue}
                    onChange={(e) => setWinData({ ...winData, actualValue: parseFloat(e.target.value) })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('crm.reasonForWinning')} <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={winData.wonReason}
                    onChange={(e) => setWinData({ ...winData, wonReason: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500"
                    placeholder={t('crm.winPlaceholder')}
                  />
                </div>
              </div>
              <div className="flex items-center justify-end gap-3 mt-6">
                <button
                  onClick={() => setShowWinDialog(false)}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                  disabled={submitting}
                >
                  {t('common.cancel')}
                </button>
                <button
                  onClick={handleWin}
                  className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {t('crm.markWon')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Lose Dialog */}
      {showLoseDialog && deal && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowLoseDialog(false)} />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-red-100 p-3 rounded-full">
                  <TrendingDown className="h-6 w-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">{t('crm.markDealLost')}</h3>
                  <p className="text-sm text-gray-600">{deal.name}</p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {t('crm.reasonForLosing')} <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    value={loseData.lostReason}
                    onChange={(e) => setLoseData({ ...loseData, lostReason: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
                    placeholder={t('crm.losePlaceholder')}
                  />
                </div>
              </div>
              <div className="flex items-center justify-end gap-3 mt-6">
                <button
                  onClick={() => setShowLoseDialog(false)}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                  disabled={submitting}
                >
                  {t('common.cancel')}
                </button>
                <button
                  onClick={handleLose}
                  className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {t('crm.markLost')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Cost Sheet Modal */}
      <Modal isOpen={showCostSheetModal} onClose={() => setShowCostSheetModal(false)} title={t('crm.addCostSheet')} size="xl">
        <div className="space-y-4">
          <p className="text-sm text-gray-600">{t('crm.costSheetItems')}</p>
          {costSheetForm.items.map((item, idx) => (
            <div key={idx} className="grid grid-cols-12 gap-2 items-end">
              <input placeholder={t('crm.description')} value={item.description || ''} onChange={(e) => {
                const next = [...costSheetForm.items]; next[idx] = { ...next[idx], description: e.target.value }; setCostSheetForm({ ...costSheetForm, items: next })
              }} className="col-span-4 px-3 py-2 border rounded-lg" />
              <input placeholder={t('crm.source')} value={item.source || ''} onChange={(e) => {
                const next = [...costSheetForm.items]; next[idx] = { ...next[idx], source: e.target.value }; setCostSheetForm({ ...costSheetForm, items: next })
              }} className="col-span-2 px-3 py-2 border rounded-lg" />
              <input type="number" placeholder="Cost" value={item.cost || ''} onChange={(e) => {
                const next = [...costSheetForm.items]; next[idx] = { ...next[idx], cost: parseFloat(e.target.value) || 0 }; const total = next.reduce((s, i) => s + (i.cost || 0) * (i.quantity || 1), 0); setCostSheetForm({ ...costSheetForm, items: next, totalCost: total })
              }} className="col-span-2 px-3 py-2 border rounded-lg" />
              <input type="number" placeholder="Qty" value={item.quantity || 1} onChange={(e) => {
                const next = [...costSheetForm.items]; next[idx] = { ...next[idx], quantity: parseInt(e.target.value) || 1 }; const total = next.reduce((s, i) => s + (i.cost || 0) * (i.quantity || 1), 0); setCostSheetForm({ ...costSheetForm, items: next, totalCost: total })
              }} className="col-span-2 px-3 py-2 border rounded-lg" />
              <button type="button" onClick={() => setCostSheetForm({ ...costSheetForm, items: costSheetForm.items.filter((_, i) => i !== idx) })} className="col-span-2 py-2 text-red-600 hover:bg-red-50 rounded">×</button>
            </div>
          ))}
          <button type="button" onClick={() => setCostSheetForm({ ...costSheetForm, items: [...costSheetForm.items, { description: '', source: '', cost: 0, quantity: 1 }] })} className="text-sm text-green-600 hover:underline">
            + {t('crm.addRow')}
          </button>
          <div className="grid grid-cols-3 gap-4 pt-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.totalCost')}</label>
              <input type="number" value={costSheetForm.totalCost || ''} onChange={(e) => setCostSheetForm({ ...costSheetForm, totalCost: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.suggestedPrice')}</label>
              <input type="number" value={costSheetForm.suggestedPrice || ''} onChange={(e) => setCostSheetForm({ ...costSheetForm, suggestedPrice: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.profitMargin')} (%)</label>
              <input type="number" value={costSheetForm.profitMargin || ''} onChange={(e) => setCostSheetForm({ ...costSheetForm, profitMargin: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button onClick={() => setShowCostSheetModal(false)} className="px-4 py-2 border rounded-lg">{t('common.cancel')}</button>
            <button onClick={handleCreateCostSheet} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg disabled:opacity-50">
              {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
              {t('common.save')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Contract Modal */}
      <Modal isOpen={showContractModal} onClose={() => setShowContractModal(false)} title={t('crm.addContract')} size="xl">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.contractTitle')} *</label>
            <input value={contractForm.title} onChange={(e) => setContractForm({ ...contractForm, title: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.contractType')}</label>
              <select value={contractForm.type} onChange={(e) => setContractForm({ ...contractForm, type: e.target.value })} className="w-full px-3 py-2 border rounded-lg">
                <option value="SALES">{t('crm.contractTypeSales')}</option>
                <option value="SERVICE">{t('crm.contractTypeService')}</option>
                <option value="MAINTENANCE">{t('crm.contractTypeMaintenance')}</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.contractValue')} *</label>
              <input type="number" value={contractForm.value || ''} onChange={(e) => setContractForm({ ...contractForm, value: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.startDate')} *</label>
              <input type="date" value={contractForm.startDate} onChange={(e) => setContractForm({ ...contractForm, startDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.endDate')}</label>
              <input type="date" value={contractForm.endDate || ''} onChange={(e) => setContractForm({ ...contractForm, endDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.paymentTerms')}</label>
            <input placeholder="e.g. Net 30" value={typeof contractForm.paymentTerms === 'object' && contractForm.paymentTerms?.description ? (contractForm.paymentTerms as any).description : ''} onChange={(e) => setContractForm({ ...contractForm, paymentTerms: { description: e.target.value } })} className="w-full px-3 py-2 border rounded-lg" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.deliveryTerms')}</label>
            <input placeholder="e.g. FOB" value={typeof contractForm.deliveryTerms === 'object' && contractForm.deliveryTerms?.description ? (contractForm.deliveryTerms as any).description : ''} onChange={(e) => setContractForm({ ...contractForm, deliveryTerms: { description: e.target.value } })} className="w-full px-3 py-2 border rounded-lg" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.terms')}</label>
            <textarea value={contractForm.terms} onChange={(e) => setContractForm({ ...contractForm, terms: e.target.value })} rows={3} className="w-full px-3 py-2 border rounded-lg" />
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button onClick={() => setShowContractModal(false)} className="px-4 py-2 border rounded-lg">{t('common.cancel')}</button>
            <button onClick={handleCreateContract} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg disabled:opacity-50">
              {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
              {t('common.save')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Invoice Modal */}
      <Modal isOpen={showInvoiceModal} onClose={() => setShowInvoiceModal(false)} title={t('crm.addInvoice')} size="xl">
        <div className="space-y-4">
          <p className="text-sm text-gray-600">{t('crm.invoiceItems')}</p>
          {invoiceForm.items.map((item, idx) => (
            <div key={idx} className="grid grid-cols-12 gap-2 items-end">
              <input placeholder={t('crm.description')} value={item.description || ''} onChange={(e) => { const next = [...invoiceForm.items]; next[idx] = { ...next[idx], description: e.target.value }; setInvoiceForm({ ...invoiceForm, items: next }) }} className="col-span-4 px-3 py-2 border rounded-lg" />
              <input type="number" placeholder="Qty" value={item.quantity || 1} onChange={(e) => {
                const next = [...invoiceForm.items]; next[idx] = { ...next[idx], quantity: parseInt(e.target.value) || 1, unitPrice: next[idx].unitPrice || 0 }; next[idx].total = (next[idx].quantity || 0) * (next[idx].unitPrice || 0); const sub = next.reduce((s, i) => s + ((i.quantity || 0) * (i.unitPrice || 0)), 0); setInvoiceForm({ ...invoiceForm, items: next, subtotal: sub, total: sub + invoiceForm.taxAmount })
              }} className="col-span-2 px-3 py-2 border rounded-lg" />
              <input type="number" placeholder="Unit Price" value={item.unitPrice || ''} onChange={(e) => {
                const next = [...invoiceForm.items]; next[idx] = { ...next[idx], unitPrice: parseFloat(e.target.value) || 0 }; next[idx].total = (next[idx].quantity || 0) * (next[idx].unitPrice || 0); const sub = next.reduce((s, i) => s + ((i.quantity || 0) * (i.unitPrice || 0)), 0); setInvoiceForm({ ...invoiceForm, items: next, subtotal: sub, total: sub + invoiceForm.taxAmount })
              }} className="col-span-2 px-3 py-2 border rounded-lg" />
              <span className="col-span-2 py-2 text-gray-600">{(item.quantity || 0) * (item.unitPrice || 0)}</span>
              <button type="button" onClick={() => setInvoiceForm({ ...invoiceForm, items: invoiceForm.items.filter((_, i) => i !== idx) })} className="col-span-2 py-2 text-red-600 hover:bg-red-50 rounded">×</button>
            </div>
          ))}
          <button type="button" onClick={() => setInvoiceForm({ ...invoiceForm, items: [...invoiceForm.items, { description: '', quantity: 1, unitPrice: 0, total: 0 }] })} className="text-sm text-green-600 hover:underline">
            + {t('crm.addRow')}
          </button>
          <div className="grid grid-cols-4 gap-4 pt-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.subtotal')}</label>
              <input type="number" value={invoiceForm.subtotal || ''} onChange={(e) => setInvoiceForm({ ...invoiceForm, subtotal: parseFloat(e.target.value) || 0, total: (parseFloat(e.target.value) || 0) + invoiceForm.taxAmount })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.taxAmount')}</label>
              <input type="number" value={invoiceForm.taxAmount || ''} onChange={(e) => setInvoiceForm({ ...invoiceForm, taxAmount: parseFloat(e.target.value) || 0, total: invoiceForm.subtotal + (parseFloat(e.target.value) || 0) })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.total')}</label>
              <input type="number" value={invoiceForm.total || ''} onChange={(e) => setInvoiceForm({ ...invoiceForm, total: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.dueDate')} *</label>
              <input type="date" value={invoiceForm.dueDate} onChange={(e) => setInvoiceForm({ ...invoiceForm, dueDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button onClick={() => setShowInvoiceModal(false)} className="px-4 py-2 border rounded-lg">{t('common.cancel')}</button>
            <button onClick={handleCreateInvoice} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg disabled:opacity-50">
              {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
              {t('common.save')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Record Payment Modal */}
      {showPaymentModal && (
        <Modal isOpen={!!showPaymentModal} onClose={() => setShowPaymentModal(null)} title={t('crm.recordPayment')}>
          <div className="space-y-4">
            <p className="text-sm text-gray-600">{showPaymentModal.invoiceNumber} · {Number(showPaymentModal.total)?.toLocaleString()} SAR</p>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.paidAmount')} *</label>
              <input type="number" value={paymentForm.paidAmount || ''} onChange={(e) => setPaymentForm({ ...paymentForm, paidAmount: parseFloat(e.target.value) || 0 })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">{t('crm.paidDate')}</label>
              <input type="date" value={paymentForm.paidDate} onChange={(e) => setPaymentForm({ ...paymentForm, paidDate: e.target.value })} className="w-full px-3 py-2 border rounded-lg" />
            </div>
            <div className="flex justify-end gap-3 pt-4">
              <button onClick={() => setShowPaymentModal(null)} className="px-4 py-2 border rounded-lg">{t('common.cancel')}</button>
              <button onClick={handleRecordPayment} disabled={submitting} className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg disabled:opacity-50">
                {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                {t('crm.recordPayment')}
              </button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

export default function DealDetailPage() {
  return (
    <ProtectedRoute>
      <DealDetailContent />
    </ProtectedRoute>
  )
}
