// app/components/admin/leads/CustomPlansTable.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 CustomPlanDetailModal from './CustomPlanDetailModal';

interface CustomPlan extends BaseTableItem {
  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 CustomPlansTableProps {
  initialData?: {
    plans: CustomPlan[];
    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 CustomPlansTable({ initialData }: CustomPlansTableProps) {
  const [plans, setPlans] = useState<CustomPlan[]>(initialData?.plans || []);
  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 [selectedPlan, setSelectedPlan] = useState<CustomPlan | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  // Check permissions
  const canViewPlan = hasPermission(PERMISSIONS.CUSTOM_PLANS_VIEW);
  const canUpdateStatus = hasPermission(PERMISSIONS.CUSTOM_PLANS_UPDATE);
  const canDeletePlan = hasPermission(PERMISSIONS.CUSTOM_PLANS_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name, email, or company...'
    },
    {
      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 plans with filters and pagination
  const fetchPlans = useCallback(async (page = 1, newFilters = filters) => {
    if (!canViewPlan) return;
    
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters
      });

      const response = await fetch(`/api/backend/admin/custom-plans?${params}`);
      const data = await response.json();

      if (response.ok) {
        setPlans(data.plans);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view custom plans');
        } else {
          toast.error(data.error || 'Failed to fetch plans');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch plans');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [canViewPlan, filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchPlans(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchPlans(page);
  };

  // Handle view plan
  const handleViewPlan = (plan: CustomPlan) => {
    if (!canViewPlan) {
      toast.error('You do not have permission to view plan details');
      return;
    }
    setSelectedPlan(plan);
    setIsModalOpen(true);
  };

  // Handle status update
  const updatePlanStatus = async (planId: number, newStatus: string) => {
    if (!canUpdateStatus) {
      toast.error('You do not have permission to update plan status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/custom-plans/${planId}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`Plan status updated to ${newStatus}`);
        fetchPlans(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update status');
      }
    } catch (error) {
      toast.error('Failed to update status');
      console.error(error);
    }
  };

  // Handle plan deletion
  const handleDeleteClick = (plan: CustomPlan) => {
    if (!canDeletePlan) {
      toast.error('You do not have permission to delete plans');
      return;
    }

    showAlert({
      title: 'Delete Inquiry',
      message: `Are you sure you want to delete inquiry from "${plan.full_name}"? This action cannot be undone.`,
      confirmText: 'Delete Inquiry',
      cancelText: 'Cancel',
      onConfirm: () => deletePlan(plan.id),
    });
  };

  const deletePlan = async (planId: number) => {
    try {
      const response = await fetch(`/api/backend/admin/custom-plans/${planId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Inquiry deleted successfully');
        fetchPlans(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete inquiry');
      }
    } catch (error) {
      toast.error('Failed to delete inquiry');
      console.error(error);
    }
  };

  // Table columns configuration
  const columns: TableColumn<CustomPlan>[] = [
    {
      key: 'customer',
      label: 'Customer',
      render: (plan) => (
        <div>
          <div className="text-sm font-medium text-var-text">{plan.full_name}</div>
          <div className="text-xs text-var-text-muted">{plan.email}</div>
        </div>
      )
    },
    {
      key: 'company',
      label: 'Company',
      render: (plan) => (
        <div>
          <div className="text-sm font-medium text-var-text">{plan.company}</div>
          {plan.phone && <div className="text-xs text-var-text-muted">{plan.phone}</div>}
        </div>
      )
    },
    {
      key: 'website',
      label: 'Website',
      render: (plan) => (
        <a
          href={`https://${plan.website}`}
          target="_blank"
          rel="noopener noreferrer"
          className="text-sm text-var-primary hover:underline"
        >
          {plan.website}
        </a>
      )
    },
    {
      key: 'budget',
      label: 'Budget',
      render: (plan) => (
        <span className="text-sm text-var-text">{plan.monthly_budget || '-'}</span>
      )
    },
    {
      key: 'posts',
      label: 'Posts',
      render: (plan) => (
        <span className="text-sm text-var-text">{plan.post_count || '-'}</span>
      )
    },
    {
      key: 'status_badge',
      label: 'Status',
      render: (plan) => (
        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${statusColors[plan.status]}`}>
          {plan.status.replace('_', ' ').toUpperCase()}
        </span>
      )
    },
    {
      key: 'status_update',
      label: 'Update Status',
      render: (plan) => (
        <select
          value={plan.status}
          onChange={(e) => updatePlanStatus(plan.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: (plan) => (
        <div>
          <div className="text-sm text-var-text">
            {new Date(plan.created_at).toLocaleDateString()}
          </div>
          <div className="text-xs text-var-text-muted">
            {new Date(plan.created_at).toLocaleTimeString()}
          </div>
        </div>
      )
    }
  ];

  // Actions for the table
  const actions = [
    ...(canViewPlan ? [{
      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: (plan: CustomPlan) => handleViewPlan(plan),
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
    }] : []),
    ...(canDeletePlan ? [{
      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: (plan: CustomPlan) => handleDeleteClick(plan),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchPlans();
    }
  }, [fetchPlans, 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">Custom Plan Inquiries</h2>
              <p className="text-sm text-var-text-secondary mt-1">
                {pagination.total} inquiry{pagination.total !== 1 ? 'ies' : ''} 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={plans}
          columns={columns}
          actions={actions}
          loading={loading}
          emptyMessage="No custom plan inquiries found"
          emptyDescription="Try adjusting your search or filters"
          keyExtractor={(plan) => plan.id.toString()}
        />

        {/* Pagination */}
        <TablePagination
          pagination={pagination}
          onPageChange={handlePageChange}
        />
      </div>

      {/* Plan Detail Modal */}
      {selectedPlan && (
        <CustomPlanDetailModal
          isOpen={isModalOpen}
          onClose={() => {
            setIsModalOpen(false);
            setSelectedPlan(null);
          }}
          plan={selectedPlan}
          onUpdate={() => fetchPlans(pagination.page)}
          canUpdateStatus={canUpdateStatus}
        />
      )}
    </>
  );
}