'use client';

import React from 'react';
import styles from '../commonstyle/dattabale.module.css';
import { FaSearchLocation } from 'react-icons/fa';
import { FcPrint } from 'react-icons/fc';
import { FiBarChart2, FiRefreshCw, FiEyeOff, FiGitBranch, FiUser } from 'react-icons/fi';

// ✅ NEW — Submitter option type
export interface SubmitterOption {
  id: number;
  firstName?: string;
  lastName?: string;
  email?: string;
}

interface InquiryFiltersProps {
  searchTerm:            string;
  setSearchTerm:         (v: string) => void;
  statusFilter:          string;
  setStatusFilter:       (v: string) => void;
  monthFilter:           string;
  setMonthFilter:        (v: string) => void;
  clearFilters:          () => void;
  onRefresh?:            () => void;
  onAnalyticsToggle?:    () => void;
  showAnalytics?:        boolean;
  onPipelineView?:       () => void;

  // ✅ NEW — User filter (only visible if showUserFilter is true)
  showUserFilter?:       boolean;
  userFilter?:           string;
  setUserFilter?:        (v: string) => void;
  submitters?:           SubmitterOption[];
}

const STATUS_OPTIONS = [
  { value: 'all',               label: 'All Statuses'       },
  { value: 'PENDING',           label: 'Pending'            },
  { value: 'IN_REVIEW',         label: 'In Review'          },
  { value: 'DRAFT_READY',       label: 'Draft Ready'        },
  { value: 'CHANGES_REQUESTED', label: 'Changes Requested'  },
  { value: 'CLIENT_CONFIRMED',  label: 'Client Confirmed'   },
  { value: 'FINAL_ISSUED',      label: 'Final Issued'       },
];

const MONTHS = [
  { value: 'all', label: 'All Months'  },
  { value: '01',  label: 'January'     },
  { value: '02',  label: 'February'    },
  { value: '03',  label: 'March'       },
  { value: '04',  label: 'April'       },
  { value: '05',  label: 'May'         },
  { value: '06',  label: 'June'        },
  { value: '07',  label: 'July'        },
  { value: '08',  label: 'August'      },
  { value: '09',  label: 'September'   },
  { value: '10',  label: 'October'     },
  { value: '11',  label: 'November'    },
  { value: '12',  label: 'December'    },
];

// ✅ Build display label for a submitter
const formatSubmitter = (u: SubmitterOption): string => {
  const name = `${u.firstName ?? ''} ${u.lastName ?? ''}`.trim();
  if (name) return name;
  if (u.email) return u.email;
  return `User #${u.id}`;
};

export const InquiryFilters = ({
  searchTerm,    setSearchTerm,
  statusFilter,  setStatusFilter,
  monthFilter,   setMonthFilter,
  clearFilters,  onRefresh,
  onAnalyticsToggle, showAnalytics = false,
  onPipelineView,
  showUserFilter = false,
  userFilter = 'all',
  setUserFilter,
  submitters = [],
}: InquiryFiltersProps) => {

  // ✅ Active filter count for visual feedback
  const activeFilters = [
    searchTerm,
    statusFilter !== 'all' ? statusFilter : null,
    monthFilter !== 'all' ? monthFilter : null,
    userFilter !== 'all' ? userFilter : null,
  ].filter(Boolean).length;

  return (
    <div className={styles.toolbar}>
      {/* ── Top Row ── */}
      <div className={styles.toolbarTop}>
        <div className={styles.searchBox}>
          <span className={styles.searchIcon}><FaSearchLocation /></span>
          <input
            type="text"
            aria-label="Search Inquiries"
            placeholder="Search by company name or inquiry ref..."
            className={styles.searchInput}
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
          />
        </div>

        <div className={styles.toolbarActions}>
          {onPipelineView && (
            <button
              title="View Inquiry Pipeline"
              onClick={onPipelineView}
              style={{
                display: 'flex', alignItems: 'center', gap: 6,
                padding: '8px 16px',
                background: 'linear-gradient(135deg, #0f766e 0%, #14b8a6 100%)',
                color: 'white', border: 'none', borderRadius: 8,
                fontSize: '0.875rem', fontWeight: 600, cursor: 'pointer',
                whiteSpace: 'nowrap',
              }}>
              <FiGitBranch size={16} /> Pipeline
            </button>
          )}

          {onAnalyticsToggle && (
            <button
              title={showAnalytics ? 'Hide Analytics' : 'Show Analytics'}
              onClick={onAnalyticsToggle}
              style={{
                display: 'flex', alignItems: 'center', gap: 6,
                padding: '8px 16px',
                background: showAnalytics
                  ? 'linear-gradient(135deg,#10b981,#059669)'
                  : 'linear-gradient(135deg,#667eea,#764ba2)',
                color: 'white', border: 'none', borderRadius: 8,
                fontSize: '0.875rem', fontWeight: 600, cursor: 'pointer',
              }}>
              {showAnalytics
                ? <><FiEyeOff size={16} /> Hide Analytics</>
                : <><FiBarChart2 size={16} /> Analytics</>}
            </button>
          )}

          <button className={styles.btnIcon} title="Print"><FcPrint /></button>
          <button className={styles.btnIcon} title="Refresh" onClick={onRefresh}><FiRefreshCw size={16} /></button>
        </div>
      </div>

      {/* ── Bottom Row: Filters ── */}
      <div
        className={styles.toolbarFilters}
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          alignItems: 'center',
          gap: 10,
          padding: '12px 14px',
          background: '#f8fafc',
          border: '1px solid #e2e8f0',
          borderRadius: 10,
        }}
      >
        {/* Filter label */}
        <span style={{
          fontSize: 11,
          fontWeight: 700,
          color: '#64748b',
          textTransform: 'uppercase',
          letterSpacing: '0.05em',
          marginRight: 4,
        }}>
          🔍 Filters:
        </span>

        {/* Status filter */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <select
            className={styles.filterSelect}
            value={statusFilter}
            onChange={e => setStatusFilter(e.target.value)}
            style={{
              minWidth: 160,
              padding: '7px 12px',
              borderRadius: 8,
              border: statusFilter !== 'all' ? '1.5px solid #0f766e' : '1px solid #cbd5e1',
              background: statusFilter !== 'all' ? '#f0fdfa' : '#fff',
              fontSize: 13,
              fontWeight: 600,
              color: statusFilter !== 'all' ? '#0f766e' : '#475569',
              cursor: 'pointer',
              outline: 'none',
            }}
          >
            {STATUS_OPTIONS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
          </select>
        </div>

        {/* Month filter */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <select
            className={styles.filterSelect}
            value={monthFilter}
            onChange={e => setMonthFilter(e.target.value)}
            style={{
              minWidth: 140,
              padding: '7px 12px',
              borderRadius: 8,
              border: monthFilter !== 'all' ? '1.5px solid #0f766e' : '1px solid #cbd5e1',
              background: monthFilter !== 'all' ? '#f0fdfa' : '#fff',
              fontSize: 13,
              fontWeight: 600,
              color: monthFilter !== 'all' ? '#0f766e' : '#475569',
              cursor: 'pointer',
              outline: 'none',
            }}
          >
            {MONTHS.map(m => <option key={m.value} value={m.value}>{m.label}</option>)}
          </select>
        </div>

        {/* ✅ User filter — visually distinct teal accent */}
        {showUserFilter && setUserFilter && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 6,
              padding: '4px 10px 4px 8px',
              borderRadius: 8,
              background: userFilter !== 'all' ? '#ecfeff' : 'transparent',
              border: userFilter !== 'all' ? '1px solid #67e8f9' : '1px solid transparent',
            }}
          >
            <FiUser size={14} style={{ color: '#0891b2', flexShrink: 0 }} />
            <select
              className={styles.filterSelect}
              value={userFilter}
              onChange={e => setUserFilter(e.target.value)}
              style={{
                minWidth: 200,
                padding: '6px 10px',
                borderRadius: 6,
                border: userFilter !== 'all' ? '1.5px solid #0891b2' : '1px solid #cbd5e1',
                background: '#fff',
                fontSize: 13,
                fontWeight: 600,
                color: userFilter !== 'all' ? '#0e7490' : '#475569',
                cursor: 'pointer',
                outline: 'none',
              }}
              title="Filter by user who submitted the inquiry"
            >
              <option value="all">👥 All Users ({submitters.length})</option>
              {submitters.length === 0 ? (
                <option value="" disabled>— No users found —</option>
              ) : (
                submitters.map(u => (
                  <option key={u.id} value={String(u.id)}>
                    {formatSubmitter(u)}
                  </option>
                ))
              )}
            </select>
          </div>
        )}

        {/* Clear button — show only when filters are active */}
        {activeFilters > 0 && (
          <button
            onClick={clearFilters}
            type="button"
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 5,
              padding: '7px 14px',
              borderRadius: 8,
              border: '1px solid #fca5a5',
              background: '#fef2f2',
              color: '#dc2626',
              cursor: 'pointer',
              fontSize: 12,
              fontWeight: 700,
              marginLeft: 'auto',
            }}
            title={`Clear ${activeFilters} active filter${activeFilters > 1 ? 's' : ''}`}
          >
            ✕ Clear ({activeFilters})
          </button>
        )}
      </div>
    </div>
  );
};

export default InquiryFilters;