// app/components/admin/leads/AuditLeadsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import toast from 'react-hot-toast';
import { usePermissions } from '@/hooks/usePermissions';
import { PERMISSIONS } from '@/lib/permissions';
import { useAlert } from '@/contexts/AlertContext';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, PaginationData, TableColumn } from '@/types/admin-table';
import AuditLeadDetailModal from './AuditLeadDetailModal';

interface AuditLead extends BaseTableItem {
  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 AuditLeadsTableProps {
  initialData?: {
    leads: AuditLead[];
    pagination: PaginationData;
  };
}

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 AuditLeadsTable({ initialData }: AuditLeadsTableProps) {
  const [leads, setLeads] = useState<AuditLead[]>(initialData?.leads || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationData>(initialData?.pagination || {
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [filters, setFilters] = useState<FilterValues>({
    search: '',
    status: '',
    industry: ''
  });
  const [selectedLead, setSelectedLead] = useState<AuditLead | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  // Check permissions
  const canViewLead = hasPermission(PERMISSIONS.LEADS_VIEW);
  const canUpdateStatus = hasPermission(PERMISSIONS.LEADS_UPDATE);
  const canDeleteLead = hasPermission(PERMISSIONS.LEADS_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name, email, or website...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: statusOptions
    },
    {
      key: 'industry',
      label: 'Industry',
      type: 'select',
      options: [
        { value: 'technology', label: 'Technology' },
        { value: 'ecommerce', label: 'E-commerce' },
        { value: 'healthcare', label: 'Healthcare' },
        { value: 'finance', label: 'Finance' },
        { value: 'education', label: 'Education' },
        { value: 'real estate', label: 'Real Estate' },
        { value: 'travel', label: 'Travel' },
        { value: 'other', label: 'Other' }
      ]
    }
  ];

  // Fetch leads with filters and pagination
  const fetchLeads = useCallback(async (page = 1, newFilters = filters) => {
    if (!canViewLead) return;
    
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters
      });

      const response = await fetch(`/api/backend/admin/audit-leads?${params}`);
      const data = await response.json();

      if (response.ok) {
        setLeads(data.leads);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view audit leads');
        } else {
          toast.error(data.error || 'Failed to fetch leads');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch leads');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [canViewLead, filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchLeads(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchLeads(page);
  };

  // Handle view lead
  const handleViewLead = (lead: AuditLead) => {
    if (!canViewLead) {
      toast.error('You do not have permission to view lead details');
      return;
    }
    setSelectedLead(lead);
    setIsModalOpen(true);
  };

  // Handle status update
  const updateLeadStatus = async (leadId: number, newStatus: string) => {
    if (!canUpdateStatus) {
      toast.error('You do not have permission to update lead status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/audit-leads/${leadId}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`Lead status updated to ${newStatus}`);
        fetchLeads(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch (error) {
      toast.error('Failed to update status');
      console.error(error);
    }
  };

  // Handle lead deletion
  const handleDeleteClick = (lead: AuditLead) => {
    if (!canDeleteLead) {
      toast.error('You do not have permission to delete leads');
      return;
    }

    showAlert({
      title: 'Delete Lead',
      message: `Are you sure you want to delete lead from "${lead.full_name}"? This action cannot be undone.`,
      confirmText: 'Delete Lead',
      cancelText: 'Cancel',
      onConfirm: () => deleteLead(lead.id),
    });
  };

  const deleteLead = async (leadId: number) => {
    try {
      const response = await fetch(`/api/backend/admin/audit-leads/${leadId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Lead deleted successfully');
        fetchLeads(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete lead');
      }
    } catch (error) {
      toast.error('Failed to delete lead');
      console.error(error);
    }
  };

  // Table columns configuration
  const columns: TableColumn<AuditLead>[] = [
    {
      key: 'customer',
      label: 'Customer',
      render: (lead) => (
        <div>
          <div className="text-sm font-medium text-var-text">{lead.full_name}</div>
          <div className="text-xs text-var-text-muted">{lead.email}</div>
        </div>
      )
    },
    {
      key: 'website',
      label: 'Website',
      render: (lead) => (
        <a
          href={`https://${lead.website}`}
          target="_blank"
          rel="noopener noreferrer"
          className="text-sm text-var-primary hover:underline"
        >
          {lead.website}
        </a>
      )
    },
    {
      key: 'company',
      label: 'Company',
      render: (lead) => (
        <span className="text-sm text-var-text">{lead.company || '-'}</span>
      )
    },
    {
      key: 'industry',
      label: 'Industry',
      render: (lead) => (
        <span className="text-sm text-var-text capitalize">{lead.industry || '-'}</span>
      )
    },
    {
      key: 'goals',
      label: 'Goals',
      render: (lead) => (
        <div className="flex flex-wrap gap-1">
          {lead.goals?.slice(0, 2).map((goal, idx) => (
            <span key={idx} className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-surface-hover text-var-text-secondary">
              {goal}
            </span>
          ))}
          {lead.goals && lead.goals.length > 2 && (
            <span className="text-xs text-var-text-muted">+{lead.goals.length - 2}</span>
          )}
        </div>
      )
    },
    {
      key: 'status_badge',
      label: 'Status',
      render: (lead) => (
        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${statusColors[lead.status]}`}>
          {lead.status.replace('_', ' ').toUpperCase()}
        </span>
      )
    },
    {
      key: 'status_update',
      label: 'Update Status',
      render: (lead) => (
        <select
          value={lead.status}
          onChange={(e) => updateLeadStatus(lead.id, e.target.value)}
          className="text-xs border border-var-border bg-var-input text-var-text rounded-lg px-2 py-1 focus:ring-2 focus:ring-var-primary focus:border-transparent"
          onClick={(e) => e.stopPropagation()}
        >
          {statusOptions.map(option => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (lead) => (
        <div>
          <div className="text-sm text-var-text">
            {new Date(lead.created_at).toLocaleDateString()}
          </div>
          <div className="text-xs text-var-text-muted">
            {new Date(lead.created_at).toLocaleTimeString()}
          </div>
        </div>
      )
    }
  ];

  // Actions for the table
  const actions = [
    ...(canViewLead ? [{
      key: 'view',
      label: 'View',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
      ),
      onClick: (lead: AuditLead) => handleViewLead(lead),
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
    }] : []),
    ...(canDeleteLead ? [{
      key: 'delete',
      label: 'Delete',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
      ),
      onClick: (lead: AuditLead) => handleDeleteClick(lead),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchLeads();
    }
  }, [fetchLeads, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <>
      <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
            <div>
              <h2 className="text-lg font-semibold text-var-text">Audit Leads</h2>
              <p className="text-sm text-var-text-secondary mt-1">
                {pagination.total} lead{pagination.total !== 1 ? 's' : ''} found
              </p>
            </div>
            
            {/* Filter Toggle Button */}
            <button
              onClick={toggleFilters}
              className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
              title={filtersVisible ? "Hide filters" : "Show filters"}
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              {filtersVisible ? 'Hide Filters' : 'Show Filters'}
            </button>
          </div>

          {/* Filters - Conditionally rendered */}
          {filtersVisible && (
            <div className="mt-4">
              <TableFilters
                filters={filterConfigs}
                onFilterChange={handleFilterChange}
                initialValues={filters}
                className="mt-0"
              />
            </div>
          )}
        </div>

        {/* Data Table */}
        <DataTable
          data={leads}
          columns={columns}
          actions={actions}
          loading={loading}
          emptyMessage="No audit leads found"
          emptyDescription="Try adjusting your search or filters"
          keyExtractor={(lead) => lead.id.toString()}
        />

        {/* Pagination */}
        <TablePagination
          pagination={pagination}
          onPageChange={handlePageChange}
        />
      </div>

      {/* Lead Detail Modal */}
      {selectedLead && (
        <AuditLeadDetailModal
          isOpen={isModalOpen}
          onClose={() => {
            setIsModalOpen(false);
            setSelectedLead(null);
          }}
          lead={selectedLead}
          onUpdate={() => fetchLeads(pagination.page)}
          canUpdateStatus={canUpdateStatus}
        />
      )}
    </>
  );
}