// app/components/admin/leads/CustomPlanDetailModal.tsx
'use client';

import { useState } from 'react';
import { X, Mail, Phone, Globe, Building, Briefcase, DollarSign, FileText, Calendar, Clock, Target, TrendingUp, Layers } from 'lucide-react';
import toast from 'react-hot-toast';

interface CustomPlan {
  id: number;
  full_name: string;
  email: string;
  company: string;
  phone: string | null;
  website: string;
  company_size: string | null;
  industry: string | null;
  monthly_budget: string | null;
  post_count: number | null;
  da_range: string[];
  timeline: string | null;
  topics: string | null;
  additional_services: string[];
  status: string;
  created_at: string;
  updated_at: string;
}

interface CustomPlanDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  plan: CustomPlan;
  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 CustomPlanDetailModal({
  isOpen,
  onClose,
  plan,
  onUpdate,
  canUpdateStatus
}: CustomPlanDetailModalProps) {
  const [selectedStatus, setSelectedStatus] = useState(plan.status);
  const [isUpdating, setIsUpdating] = useState(false);

  const handleStatusUpdate = async () => {
    if (selectedStatus === plan.status) {
      onClose();
      return;
    }

    setIsUpdating(true);
    try {
      const response = await fetch(`/api/backend/admin/custom-plans/${plan.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-4xl 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">Custom Plan Inquiry Details</h3>
              <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[plan.status]}`}>
                {plan.status.toUpperCase()}
              </span>
            </div>
            <p className="text-sm text-var-text-muted mt-1">Submitted on {new Date(plan.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 Section */}
          <div>
            <h4 className="text-md font-semibold text-var-text mb-3 flex items-center gap-2">
              <Building className="h-4 w-4 text-var-text-muted" />
              Customer Information
            </h4>
            <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:${plan.email}`} className="text-sm text-var-primary hover:underline">
                  {plan.email}
                </a>
              </div>

              {plan.phone && (
                <div className="bg-var-surface-hover rounded-xl p-4">
                  <div className="flex items-center gap-2 text-var-text-muted mb-2">
                    <Phone className="h-4 w-4" />
                    <span className="text-xs font-medium">PHONE</span>
                  </div>
                  <a href={`tel:${plan.phone}`} className="text-sm text-var-primary hover:underline">
                    {plan.phone}
                  </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://${plan.website}`} target="_blank" rel="noopener noreferrer" className="text-sm text-var-primary hover:underline">
                  {plan.website}
                </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">
                  <Briefcase className="h-4 w-4" />
                  <span className="text-xs font-medium">COMPANY SIZE</span>
                </div>
                <p className="text-sm text-var-text">{plan.company_size || 'Not specified'}</p>
              </div>
            </div>
          </div>

          {/* Business Details */}
          <div>
            <h4 className="text-md font-semibold text-var-text mb-3 flex items-center gap-2">
              <TrendingUp className="h-4 w-4 text-var-text-muted" />
              Business Details
            </h4>
            <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">
                  <Layers className="h-4 w-4" />
                  <span className="text-xs font-medium">INDUSTRY</span>
                </div>
                <p className="text-sm text-var-text capitalize">{plan.industry || 'Not specified'}</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">
                  <DollarSign className="h-4 w-4" />
                  <span className="text-xs font-medium">MONTHLY BUDGET</span>
                </div>
                <p className="text-sm text-var-text">{plan.monthly_budget || 'Not specified'}</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">
                  <FileText className="h-4 w-4" />
                  <span className="text-xs font-medium">POST COUNT</span>
                </div>
                <p className="text-sm text-var-text">{plan.post_count || 'Not specified'}</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">
                  <Calendar className="h-4 w-4" />
                  <span className="text-xs font-medium">TIMELINE</span>
                </div>
                <p className="text-sm text-var-text">{plan.timeline || 'Not specified'}</p>
              </div>
            </div>
          </div>

          {/* DA Range */}
          {plan.da_range && plan.da_range.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">DA RANGE PREFERENCE</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {plan.da_range.map((range, idx) => (
                  <span key={idx} className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-var-info-bg text-var-info-text">
                    DA {range}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Additional Services */}
          {plan.additional_services && plan.additional_services.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">
                <Layers className="h-4 w-4" />
                <span className="text-xs font-medium">ADDITIONAL SERVICES</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {plan.additional_services.map((service, idx) => (
                  <span key={idx} className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-var-success-bg text-var-success-text">
                    {service}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Topics */}
          {plan.topics && (
            <div className="bg-var-surface-hover rounded-xl p-4">
              <div className="flex items-center gap-2 text-var-text-muted mb-3">
                <FileText className="h-4 w-4" />
                <span className="text-xs font-medium">TOPICS / NICHE</span>
              </div>
              <p className="text-sm text-var-text whitespace-pre-wrap">{plan.topics}</p>
            </div>
          )}

          {/* Meta 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">
                <Clock className="h-4 w-4" />
                <span className="text-xs font-medium">CREATED AT</span>
              </div>
              <p className="text-sm text-var-text">{new Date(plan.created_at).toLocaleString()}</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">
                <Calendar className="h-4 w-4" />
                <span className="text-xs font-medium">LAST UPDATED</span>
              </div>
              <p className="text-sm text-var-text">{new Date(plan.updated_at).toLocaleString()}</p>
            </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 !== plan.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 Changes'}
                  </button>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}