import React, { useState, useMemo } from 'react';
import { DataTable } from '../components/DataTable';
import { PropertyCard } from '../components/PropertyCard';
import { ExportButton } from '../components/ExportButton';
import { JobStatus } from '../components/JobStatus';

interface Property {
  address?: string;
  propertyType?: string;
  units?: number;
  sqft?: number;
  yearBuilt?: number;
  lotSize?: string;
  zoning?: string;
  owner?: {
    name?: string;
    company?: string;
    portfolioSize?: number;
    phones?: Array<{ number: string; type?: string }>;
    emails?: string[];
  };
  sales?: Array<{
    date?: string;
    price?: number;
    buyer?: string;
    seller?: string;
  }>;
  debt?: Array<{
    lender?: string;
    amount?: number;
    maturityDate?: string;
    loanType?: string;
  }>;
}

interface ResultsData {
  jobId?: string;
  status?: 'pending' | 'running' | 'complete' | 'error';
  properties?: Property[];
  totalCount?: number;
  searchConfig?: any;
  error?: string;
}

interface ResultsViewerProps {
  data: ResultsData;
}

export function ResultsViewer({ data }: ResultsViewerProps) {
  const [viewMode, setViewMode] = useState<'table' | 'card'>('table');
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [toast, setToast] = useState<string | null>(null);

  const properties = data?.properties || [];
  const status = data?.status || 'complete';

  // Get unique property types for filter
  const propertyTypes = useMemo(() => {
    const types = new Set(properties.map((p) => p.propertyType).filter(Boolean));
    return Array.from(types) as string[];
  }, [properties]);

  // Filter properties
  const filtered = useMemo(() => {
    return properties.filter((p) => {
      if (search) {
        const q = search.toLowerCase();
        const matchAddr = p.address?.toLowerCase().includes(q);
        const matchOwner = p.owner?.name?.toLowerCase().includes(q);
        const matchCompany = p.owner?.company?.toLowerCase().includes(q);
        if (!matchAddr && !matchOwner && !matchCompany) return false;
      }
      if (typeFilter && p.propertyType !== typeFilter) return false;
      return true;
    });
  }, [properties, search, typeFilter]);

  const showToast = (msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(null), 2500);
  };

  const fmtPrice = (n?: number) =>
    n != null ? `$${n.toLocaleString()}` : '—';

  const tableColumns = [
    {
      key: 'address',
      label: 'Address',
      width: '220px',
      render: (p: Property) => (
        <span className="font-medium text-reo-dark">{p.address || '—'}</span>
      ),
    },
    {
      key: 'propertyType',
      label: 'Type',
      render: (p: Property) =>
        p.propertyType ? <span className="badge badge-info">{p.propertyType}</span> : '—',
    },
    {
      key: 'units',
      label: 'Units',
      render: (p: Property) => p.units ?? '—',
    },
    {
      key: 'ownerName',
      label: 'Owner',
      render: (p: Property) => (
        <div>
          <span className="font-medium">{p.owner?.name || '—'}</span>
          {p.owner?.company && (
            <span className="block text-xs text-gray-400">{p.owner.company}</span>
          )}
        </div>
      ),
    },
    {
      key: 'phones',
      label: 'Phones',
      sortable: false,
      render: (p: Property) => {
        const phones = p.owner?.phones || [];
        if (phones.length === 0) return <span className="text-gray-300">—</span>;
        return (
          <div className="space-y-0.5">
            {phones.slice(0, 2).map((ph, i) => (
              <button
                key={i}
                onClick={(e) => {
                  e.stopPropagation();
                  navigator.clipboard.writeText(ph.number);
                  showToast('Phone copied!');
                }}
                className="block text-xs font-mono text-reo-dark hover:text-reo-teal transition-colors"
                title="Click to copy"
              >
                {ph.number}
                {ph.type && <span className="text-gray-400 ml-1">({ph.type})</span>}
              </button>
            ))}
            {phones.length > 2 && (
              <span className="text-xs text-gray-400">+{phones.length - 2} more</span>
            )}
          </div>
        );
      },
    },
    {
      key: 'emails',
      label: 'Emails',
      sortable: false,
      render: (p: Property) => {
        const emails = p.owner?.emails || [];
        if (emails.length === 0) return <span className="text-gray-300">—</span>;
        return (
          <div className="space-y-0.5">
            {emails.slice(0, 2).map((em, i) => (
              <button
                key={i}
                onClick={(e) => {
                  e.stopPropagation();
                  navigator.clipboard.writeText(em);
                  showToast('Email copied!');
                }}
                className="block text-xs text-reo-dark hover:text-reo-teal transition-colors truncate max-w-[180px]"
                title="Click to copy"
              >
                {em}
              </button>
            ))}
            {emails.length > 2 && (
              <span className="text-xs text-gray-400">+{emails.length - 2} more</span>
            )}
          </div>
        );
      },
    },
    {
      key: 'lastSale',
      label: 'Last Sale',
      render: (p: Property) => {
        const sale = p.sales?.[0];
        if (!sale) return '—';
        return (
          <div>
            <span className="font-medium">{fmtPrice(sale.price)}</span>
            {sale.date && <span className="block text-xs text-gray-400">{sale.date}</span>}
          </div>
        );
      },
    },
  ];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-reo-dark text-white px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <h1 className="text-lg font-bold flex items-center gap-2">
              <span className="w-7 h-7 bg-reo-teal rounded-lg flex items-center justify-center text-sm font-bold">R</span>
              Results
            </h1>
            <JobStatus status={status} />
            <span className="text-sm text-gray-400">
              {filtered.length} of {properties.length} properties
            </span>
          </div>
          <ExportButton data={filtered} filename={`reonomy-${data?.jobId || 'export'}`} />
        </div>
      </div>

      {/* Controls bar */}
      <div className="bg-white border-b border-gray-200 px-6 py-3 flex items-center gap-4">
        {/* Search */}
        <div className="relative flex-1 max-w-md">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by address or owner..."
            className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-reo-teal focus:border-reo-teal outline-none"
          />
        </div>

        {/* Type filter */}
        {propertyTypes.length > 0 && (
          <select
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-reo-teal outline-none"
          >
            <option value="">All Types</option>
            {propertyTypes.map((t) => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        )}

        {/* View toggle */}
        <div className="flex bg-gray-100 rounded-lg p-0.5">
          <button
            onClick={() => setViewMode('table')}
            className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
              viewMode === 'table' ? 'bg-white text-reo-dark shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            <svg className="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
            </svg>
            Table
          </button>
          <button
            onClick={() => setViewMode('card')}
            className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
              viewMode === 'card' ? 'bg-white text-reo-dark shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            <svg className="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
            </svg>
            Cards
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="px-6 py-5">
        {data?.error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4 text-sm text-red-700">
            ⚠️ {data.error}
          </div>
        )}

        {properties.length === 0 && !data?.error && (
          <div className="text-center py-16 text-gray-400">
            <svg className="w-12 h-12 mx-auto mb-3 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
            <p className="text-lg font-medium">No properties yet</p>
            <p className="text-sm mt-1">Results will appear here after running a search</p>
          </div>
        )}

        {viewMode === 'table' && filtered.length > 0 && (
          <DataTable
            columns={tableColumns}
            data={filtered}
            pageSize={15}
            getRowKey={(item, idx) => item.address || String(idx)}
          />
        )}

        {viewMode === 'card' && filtered.length > 0 && (
          <div className="grid gap-3 max-w-3xl">
            {filtered.map((property, idx) => (
              <PropertyCard
                key={property.address || idx}
                property={property}
                onToast={showToast}
              />
            ))}
          </div>
        )}
      </div>

      {/* Bottom export bar */}
      {filtered.length > 0 && (
        <div className="sticky bottom-0 bg-white border-t border-gray-200 px-6 py-3 flex items-center justify-between">
          <span className="text-sm text-gray-500">
            {filtered.length} {filtered.length === 1 ? 'property' : 'properties'}
            {search || typeFilter ? ' (filtered)' : ''}
          </span>
          <ExportButton data={filtered} filename={`reonomy-${data?.jobId || 'export'}`} formats={['csv']} />
        </div>
      )}

      {/* Toast */}
      {toast && <div className="toast toast-success">{toast}</div>}
    </div>
  );
}
