import { useState, useEffect } from 'react';
import ProUpsell from '../UI/ProUpsell';
import Button from '../UI/Button';
import { fetchLists } from '../../utils/api';

const HIGHLIGHTS = [
  { icon: '📊', title: 'Custom Fields', desc: 'Choose exactly which fields to include' },
  { icon: '🔍', title: 'Advanced Filters', desc: 'Filter by status, list, country, date range' },
  { icon: '📁', title: 'CSV & JSON', desc: 'Export in universal formats for any application' },
  { icon: '♾️', title: 'Up to 50k Records', desc: 'Export large datasets in one click' },
];

const ALL_FIELDS = [
  { id: 'email',         label: 'Email' },
  { id: 'name',          label: 'Name' },
  { id: 'status',        label: 'Status' },
  { id: 'form_name',     label: 'Form Name' },
  { id: 'country',       label: 'Country' },
  { id: 'country_code',  label: 'Country Code' },
  { id: 'city',          label: 'City' },
  { id: 'region',        label: 'Region' },
  { id: 'list_name',     label: 'List' },
  { id: 'created_at',    label: 'Created Date' },
  { id: 'last_activity', label: 'Last Activity' },
  { id: 'recovered_at',  label: 'Recovered Date' },
  { id: 'ip',            label: 'IP Address' },
  { id: 'form_data',     label: 'Full Form Data (JSON)' },
];

export default function Export({ isPro }) {
  if (!isPro) {
    return (
      <ProUpsell
        feature="CSV & JSON Export"
        description="Export your leads with custom field selection, advanced condition filtering, and unlimited records. Perfect for CRM imports, backups, and reporting."
        highlights={HIGHLIGHTS}
      />
    );
  }

  const [lists,          setLists]          = useState([]);
  const [format,         setFormat]         = useState('csv');
  const [selectedFields, setSelectedFields] = useState(['email', 'name', 'status', 'form_name', 'country', 'city', 'created_at']);
  const [filters,        setFilters]        = useState({ status: '', list_id: '', date_from: '', date_to: '' });
  const [limit,          setLimit]          = useState(1000);
  const [exporting,      setExporting]      = useState(false);
  const [exportError,    setExportError]    = useState(null);

  useEffect(() => {
    fetchLists().then(r => setLists(r.data || [])).catch(() => {});
  }, []);

  const toggleField = (id) => {
    setSelectedFields(prev =>
      prev.includes(id) ? prev.filter(f => f !== id) : [...prev, id]
    );
  };

  const updateFilter = (key, value) => setFilters(prev => ({ ...prev, [key]: value }));

  const handleExport = async () => {
    if (selectedFields.length === 0) { alert('Select at least one field.'); return; }
    setExporting(true);
    setExportError(null);

    try {
      const apiUrl = window.rescueFill?.apiUrl || '/wp-json/rescue/v1';
      const nonce  = window.rescueFill?.nonce  || '';

      const activeFilters = Object.fromEntries(
        Object.entries(filters).filter(([, v]) => v !== '')
      );

      const res = await fetch(`${apiUrl}/leads/export`, {
        method:  'POST',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        body: JSON.stringify({
          format,
          fields:  selectedFields,
          filters: activeFilters,
          limit:   Math.min(Number(limit) || 1000, 50000),
        }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || `Export failed (HTTP ${res.status})`);
      }

      const blob     = await res.blob();
      const url      = URL.createObjectURL(blob);
      const a        = document.createElement('a');
      a.href         = url;
      a.download     = `rescuefill-leads.${format}`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (e) {
      setExportError(e.message);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div className="space-y-5 max-w-2xl">
      <div>
        <h2 className="text-xl font-bold text-slate-900">Export Leads</h2>
        <p className="text-sm text-slate-500 mt-0.5">Download your leads as CSV or JSON with custom field selection.</p>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl p-6 space-y-6" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>

        {/* Format */}
        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">Format</label>
          <div className="flex gap-3">
            {[{ id: 'csv', label: '📄 CSV' }, { id: 'json', label: '📋 JSON' }].map(f => (
              <button key={f.id} onClick={() => setFormat(f.id)}
                className={`flex-1 py-2.5 rounded-lg border-2 text-sm font-semibold transition-all ${
                  format === f.id
                    ? 'border-indigo-500 bg-indigo-50 text-indigo-700'
                    : 'border-slate-200 text-slate-600 hover:border-slate-300'
                }`}>
                {f.label}
              </button>
            ))}
          </div>
        </div>

        {/* Fields */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm font-semibold text-slate-700">Fields to Include</label>
            <div className="flex gap-3">
              <button onClick={() => setSelectedFields(ALL_FIELDS.map(f => f.id))} className="text-xs text-indigo-600 hover:underline font-medium">
                Select All
              </button>
              <button onClick={() => setSelectedFields([])} className="text-xs text-slate-500 hover:underline font-medium">
                Clear
              </button>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-y-2 gap-x-4">
            {ALL_FIELDS.map(field => (
              <label key={field.id} className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer select-none">
                <input
                  type="checkbox"
                  checked={selectedFields.includes(field.id)}
                  onChange={() => toggleField(field.id)}
                  className="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
                />
                {field.label}
              </label>
            ))}
          </div>
        </div>

        {/* Filters */}
        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">Filters <span className="font-normal text-slate-400">(optional)</span></label>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-slate-500 mb-1 block">Status</label>
              <select
                value={filters.status}
                onChange={e => updateFilter('status', e.target.value)}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500">
                <option value="">All statuses</option>
                <option value="abandoned">Abandoned</option>
                <option value="active">Active</option>
                <option value="recovered">Recovered</option>
                <option value="submitted">Submitted</option>
              </select>
            </div>
            <div>
              <label className="text-xs text-slate-500 mb-1 block">List</label>
              <select
                value={filters.list_id}
                onChange={e => updateFilter('list_id', e.target.value)}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500">
                <option value="">All lists</option>
                {lists.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs text-slate-500 mb-1 block">From Date</label>
              <input
                type="date"
                value={filters.date_from}
                onChange={e => updateFilter('date_from', e.target.value)}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500"
              />
            </div>
            <div>
              <label className="text-xs text-slate-500 mb-1 block">To Date</label>
              <input
                type="date"
                value={filters.date_to}
                onChange={e => updateFilter('date_to', e.target.value)}
                className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500"
              />
            </div>
          </div>
        </div>

        {/* Limit */}
        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-1">Max Records</label>
          <input
            type="number"
            min={1}
            max={50000}
            value={limit}
            onChange={e => setLimit(e.target.value)}
            className="w-32 border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500"
          />
          <p className="text-xs text-slate-500 mt-1">Maximum 50,000 records per export.</p>
        </div>

        {exportError && (
          <div className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-4 py-3">
            {exportError}
          </div>
        )}

        <Button variant="primary" onClick={handleExport} loading={exporting} disabled={selectedFields.length === 0}>
          ⬇ Download {format.toUpperCase()}
        </Button>
      </div>
    </div>
  );
}
