// app/components/admin/leads/AuditLeadDetailModal.tsx
'use client';

import { useState } from 'react';
import { X, Mail, Globe, Building, Briefcase, Target, Calendar, Clock } from 'lucide-react';
import toast from 'react-hot-toast';

interface AuditLead {
  id: number;
  full_name: string;
  email: string;
  website: string;
  company: string | null;
  industry: string | null;
  monthly_traffic: string | null;
  goals: string[];
  status: string;
  created_at: string;
  updated_at: string;
}

interface AuditLeadDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  lead: AuditLead;
  onUpdate: () => void;
  canUpdateStatus: boolean;
}

const statusColors: Record<string, string> = {
  new: 'bg-var-info-bg text-var-info-text',
  contacted: 'bg-var-warning-bg text-var-warning-text',
  qualified: 'bg-var-success-bg text-var-success-text',
  proposal_sent: 'bg-var-primary-muted text-var-primary-text',
  negotiation: 'bg-var-accent-orange bg-opacity-10 text-var-accent-orange',
  won: 'bg-var-success-bg text-var-success-text',
  lost: 'bg-var-danger-bg text-var-danger-text',
  on_hold: 'bg-var-surface-hover text-var-text-muted',
};

const statusOptions = [
  { value: 'new', label: 'New' },
  { value: 'contacted', label: 'Contacted' },
  { value: 'qualified', label: 'Qualified' },
  { value: 'proposal_sent', label: 'Proposal Sent' },
  { value: 'negotiation', label: 'Negotiation' },
  { value: 'won', label: 'Won' },
  { value: 'lost', label: 'Lost' },
  { value: 'on_hold', label: 'On Hold' },
];

export default function AuditLeadDetailModal({
  isOpen,
  onClose,
  lead,
  onUpdate,
  canUpdateStatus
}: AuditLeadDetailModalProps) {
  const [selectedStatus, setSelectedStatus] = useState(lead.status);
  const [isUpdating, setIsUpdating] = useState(false);

  const handleStatusUpdate = async () => {
    if (selectedStatus === lead.status) {
      onClose();
      return;
    }

    setIsUpdating(true);
    try {
      const response = await fetch(`/api/backend/admin/audit-leads/${lead.id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: selectedStatus }),
      });

      if (response.ok) {
        toast.success(`Status updated to ${selectedStatus}`);
        onUpdate();
        onClose();
      } else {
        const data = await response.json();
        toast.error(data.error || 'Failed to update status');
      }
    } catch (error) {
        console.error('Error updating status:', error);
      toast.error('Failed to update status');
    } finally {
      setIsUpdating(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-var-surface rounded-2xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-y-auto shadow-var-modal">
        {/* Header */}
        <div className="sticky top-0 bg-var-surface border-b border-var-border px-6 py-4 flex justify-between items-center">
          <div>
            <div className="flex items-center gap-3">
              <h3 className="text-lg font-semibold text-var-text">Audit Lead Details</h3>
              <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[lead.status]}`}>
                {lead.status.toUpperCase()}
              </span>
            </div>
            <p className="text-sm text-var-text-muted mt-1">Submitted on {new Date(lead.created_at).toLocaleString()}</p>
          </div>
          <button onClick={onClose} className="text-var-text-muted hover:text-var-text">
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Customer Info */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="bg-var-surface-hover rounded-xl p-4">
              <div className="flex items-center gap-2 text-var-text-muted mb-2">
                <Mail className="h-4 w-4" />
                <span className="text-xs font-medium">EMAIL</span>
              </div>
              <a href={`mailto:${lead.email}`} className="text-sm text-var-primary hover:underline">
                {lead.email}
              </a>
            </div>

            <div className="bg-var-surface-hover rounded-xl p-4">
              <div className="flex items-center gap-2 text-var-text-muted mb-2">
                <Globe className="h-4 w-4" />
                <span className="text-xs font-medium">WEBSITE</span>
              </div>
              <a href={`https://${lead.website}`} target="_blank" rel="noopener noreferrer" className="text-sm text-var-primary hover:underline">
                {lead.website}
              </a>
            </div>

            {lead.company && (
              <div className="bg-var-surface-hover rounded-xl p-4">
                <div className="flex items-center gap-2 text-var-text-muted mb-2">
                  <Building className="h-4 w-4" />
                  <span className="text-xs font-medium">COMPANY</span>
                </div>
                <p className="text-sm text-var-text">{lead.company}</p>
              </div>
            )}

            {lead.industry && (
              <div className="bg-var-surface-hover rounded-xl p-4">
                <div className="flex items-center gap-2 text-var-text-muted mb-2">
                  <Briefcase className="h-4 w-4" />
                  <span className="text-xs font-medium">INDUSTRY</span>
                </div>
                <p className="text-sm text-var-text capitalize">{lead.industry}</p>
              </div>
            )}

            {lead.monthly_traffic && (
              <div className="bg-var-surface-hover rounded-xl p-4">
                <div className="flex items-center gap-2 text-var-text-muted mb-2">
                  <Calendar className="h-4 w-4" />
                  <span className="text-xs font-medium">MONTHLY TRAFFIC</span>
                </div>
                <p className="text-sm text-var-text">{lead.monthly_traffic}</p>
              </div>
            )}

            <div className="bg-var-surface-hover rounded-xl p-4">
              <div className="flex items-center gap-2 text-var-text-muted mb-2">
                <Clock className="h-4 w-4" />
                <span className="text-xs font-medium">LAST UPDATED</span>
              </div>
              <p className="text-sm text-var-text">{new Date(lead.updated_at).toLocaleString()}</p>
            </div>
          </div>

          {/* Goals */}
          {lead.goals && lead.goals.length > 0 && (
            <div className="bg-var-surface-hover rounded-xl p-4">
              <div className="flex items-center gap-2 text-var-text-muted mb-3">
                <Target className="h-4 w-4" />
                <span className="text-xs font-medium">GOALS</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {lead.goals.map((goal, idx) => (
                  <span key={idx} className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-var-primary-muted text-var-primary-text">
                    {goal}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Status Update */}
          {canUpdateStatus && (
            <div className="border-t border-var-border pt-4">
              <label className="block text-sm font-medium text-var-text mb-2">Update Status</label>
              <div className="flex gap-3">
                <select
                  value={selectedStatus}
                  onChange={(e) => setSelectedStatus(e.target.value)}
                  className="flex-1 px-3 py-2 bg-var-input border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary focus:border-transparent text-var-text"
                >
                  {statusOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
                {selectedStatus !== lead.status && (
                  <button
                    onClick={handleStatusUpdate}
                    disabled={isUpdating}
                    className="px-4 py-2 bg-var-primary text-white rounded-lg hover:bg-var-primary-hover transition-colors disabled:opacity-50 shadow-var-button"
                  >
                    {isUpdating ? 'Updating...' : 'Save'}
                  </button>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}