import { useParams, useNavigate, Link } from 'react-router-dom'
import { ArrowRight, User, Mail, Phone, Calendar, Globe, MessageSquare } from 'lucide-react'
import { useLead, useUpdateLeadStatus } from '@/hooks/useLeads'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { Badge } from '@/components/common/Badge'
import { PageLoading } from '@/components/common/Spinner'
import { formatDate, formatPhone } from '@/utils/formatters'
import { LEAD_STATUS_CONFIG, LEAD_STATUSES } from '@/utils/constants'
import type { LeadStatus } from '@/types/lead'
import { t, sprintf } from '@/lib/i18n'

export function LeadDetail() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  
  const { data, isLoading } = useLead(Number(id))
  const updateStatus = useUpdateLeadStatus()
  
  if (isLoading) {
    return <PageLoading />
  }
  
  const lead = data?.data?.lead
  const conversation = data?.data?.conversation
  
  if (!lead) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500">{t('Lead not found')}</p>
        <Button variant="outline" onClick={() => navigate('/leads')} className="mt-4">
          {t('Back to leads list')}
        </Button>
      </div>
    )
  }
  
  const handleStatusChange = (status: LeadStatus) => {
    updateStatus.mutate({ id: lead.id, status })
  }
  
  return (
    <div className="space-y-6 animate-fade-in">
      <PageHeader 
        title={lead.name || t('Unnamed lead')}
        subtitle={sprintf(t('Created %s'), formatDate(lead.created_at))}
      >
        <Link to="/leads">
          <Button variant="outline">
            <ArrowRight className="w-4 h-4 me-2" />
            {t('Back to list')}
          </Button>
        </Link>
      </PageHeader>
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Lead Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Contact Info */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Contact Details')}</CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-gray-100 rounded-lg">
                    <User className="w-5 h-5 text-gray-600" />
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">{t('Name')}</dt>
                    <dd className="font-medium text-gray-900">{lead.name || '-'}</dd>
                  </div>
                </div>
                
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-gray-100 rounded-lg">
                    <Mail className="w-5 h-5 text-gray-600" />
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">{t('Email')}</dt>
                    <dd className="font-medium text-gray-900">
                      {lead.email ? (
                        <a href={`mailto:${lead.email}`} className="text-primary-600 hover:underline">
                          {lead.email}
                        </a>
                      ) : '-'}
                    </dd>
                  </div>
                </div>
                
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-gray-100 rounded-lg">
                    <Phone className="w-5 h-5 text-gray-600" />
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">{t('Phone')}</dt>
                    <dd className="font-medium text-gray-900">
                      {lead.phone ? (
                        <a href={`tel:${lead.phone}`} className="text-primary-600 hover:underline">
                          {formatPhone(lead.phone)}
                        </a>
                      ) : '-'}
                    </dd>
                  </div>
                </div>
                
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-gray-100 rounded-lg">
                    <Globe className="w-5 h-5 text-gray-600" />
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">{t('Source')}</dt>
                    <dd className="font-medium text-gray-900 truncate max-w-[200px]">
                      {lead.source_page || '-'}
                    </dd>
                  </div>
                </div>
              </dl>
            </CardContent>
          </Card>
          
          {/* Conversation Summary */}
          {conversation && (
            <Card>
              <CardHeader className="flex items-center justify-between">
                <CardTitle>{t('Conversation Summary')}</CardTitle>
                <Badge variant="info">
                  <MessageSquare className="w-3 h-3 me-1" />
                  {sprintf(t('%s messages'), conversation.messages_count)}
                </Badge>
              </CardHeader>
              <CardContent>
                {lead.conversation_summary ? (
                  <p className="text-gray-700 whitespace-pre-wrap">{lead.conversation_summary}</p>
                ) : (
                  <p className="text-gray-500 italic">{t('No conversation summary')}</p>
                )}
              </CardContent>
            </Card>
          )}
          
          {/* Form Data - all submitted fields */}
          {lead.form_data && (() => {
            const formData = typeof lead.form_data === 'string'
              ? (() => { try { return JSON.parse(lead.form_data) } catch { return null } })()
              : lead.form_data
            const labels: Record<string, string> = lead.form_field_labels || {}
            return formData && typeof formData === 'object' && !Array.isArray(formData) && Object.keys(formData).length > 0
              ? (
                <Card>
                  <CardHeader>
                    <CardTitle>{lead.form_name ? sprintf(t('Form Data — %s'), lead.form_name) : t('Form Data')}</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <dl className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                      {Object.entries(formData).map(([key, value]) => (
                        <div key={key} className="bg-gray-50 rounded-lg p-3">
                          <dt className="text-gray-500 text-xs tracking-wide mb-1">{labels[key] || key}</dt>
                          <dd className="font-medium text-gray-900 break-words">
                            {value === null || value === undefined ? '-' : String(value)}
                          </dd>
                        </div>
                      ))}
                    </dl>
                  </CardContent>
                </Card>
              )
              : null
          })()}
          
          {/* UTM Data */}
          {lead.utm_data && (() => {
            const utmData = typeof lead.utm_data === 'string'
              ? (() => { try { return JSON.parse(lead.utm_data) } catch { return null } })()
              : lead.utm_data
            return utmData && typeof utmData === 'object' && !Array.isArray(utmData) && Object.keys(utmData).length > 0
              ? (
                <Card>
                  <CardHeader>
                    <CardTitle>{t('Tracking Data (UTM)')}</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <dl className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                      {Object.entries(utmData).map(([key, value]) => (
                        <div key={key}>
                          <dt className="text-gray-500">{key.replace('utm_', '')}</dt>
                          <dd className="font-medium text-gray-900">{String(value)}</dd>
                        </div>
                      ))}
                    </dl>
                  </CardContent>
                </Card>
              )
              : null
          })()}
        </div>
        
        {/* Sidebar */}
        <div className="space-y-6">
          {/* Status */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Status')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('Current Status')}
                  </label>
                  <select
                    value={lead.lead_status}
                    onChange={(e) => handleStatusChange(e.target.value as LeadStatus)}
                    disabled={updateStatus.isPending}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500"
                  >
                    {LEAD_STATUSES.map(s => (
                      <option key={s} value={s}>
                        {LEAD_STATUS_CONFIG[s].label}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t('Lead Score')}
                  </label>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 bg-gray-200 rounded-full h-2">
                      <div 
                        className={`h-2 rounded-full ${
                          lead.lead_score >= 80 ? 'bg-green-500' :
                          lead.lead_score >= 50 ? 'bg-yellow-500' : 'bg-gray-500'
                        }`}
                        style={{ width: `${lead.lead_score}%` }}
                      />
                    </div>
                    <span className="font-bold text-gray-900">{lead.lead_score}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
          
          {/* Timeline */}
          <Card>
            <CardHeader>
              <CardTitle>{t('Timeline')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex items-start gap-3">
                  <div className="p-1.5 bg-primary-100 rounded-full">
                    <Calendar className="w-4 h-4 text-primary-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">{t('Created')}</p>
                    <p className="text-xs text-gray-500">{formatDate(lead.created_at)}</p>
                  </div>
                </div>
                
                {lead.updated_at !== lead.created_at && (
                  <div className="flex items-start gap-3">
                    <div className="p-1.5 bg-gray-100 rounded-full">
                      <Calendar className="w-4 h-4 text-gray-600" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{t('Updated')}</p>
                      <p className="text-xs text-gray-500">{formatDate(lead.updated_at)}</p>
                    </div>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}










