'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,
  FiDownload,
  FiXCircle,
} from 'react-icons/fi';
import type {
  ClientSource,
  ClientTypeFilter,
} from '@/lib/api/types/clients.types';

interface Props {
  searchTerm: string;
  setSearchTerm: (v: string) => void;

  sourceFilter: 'all' | ClientSource;
  setSourceFilter: (v: 'all' | ClientSource) => void;

  typeFilter: ClientTypeFilter;
  setTypeFilter: (v: ClientTypeFilter) => void;

  statusFilter: 'all' | 'active' | 'inactive';
  setStatusFilter: (v: 'all' | 'active' | 'inactive') => void;

  clearFilters: () => void;
  onRefresh?: () => void;

  onAnalyticsToggle?: () => void;
  showAnalytics?: boolean;

  onExport?: () => void;
  canExport?: boolean;
  exporting?: boolean;
}

const SOURCE_OPTIONS: { value: 'all' | ClientSource; label: string }[] = [
  { value: 'all', label: '📁 All Sources' },
  { value: 'QRS', label: '📁 QRS' },
  { value: 'TQS', label: '📁 TQS' },
];

const TYPE_OPTIONS: { value: ClientTypeFilter; label: string }[] = [
  { value: 'All', label: 'All Records' },
  { value: 'Clients', label: '🏢 Clients' },
  { value: 'Surveillance', label: '👁 Surveillance' },
];

const STATUS_OPTIONS: { value: 'all' | 'active' | 'inactive'; label: string }[] = [
  { value: 'all', label: 'All Statuses' },
  { value: 'active', label: '🟢 Active' },
  { value: 'inactive', label: '🔴 Inactive' },
];

const selectStyle = (active: boolean, minWidth = 150): React.CSSProperties => ({
  minWidth,
  padding: '7px 12px',
  borderRadius: 8,
  border: active ? '1.5px solid #0f766e' : '1px solid #cbd5e1',
  background: active ? '#f0fdfa' : '#fff',
  fontSize: 13,
  fontWeight: 600,
  color: active ? '#0f766e' : '#475569',
  cursor: 'pointer',
  outline: 'none',
});

export default function ClientsFilters({
  searchTerm,
  setSearchTerm,
  sourceFilter,
  setSourceFilter,
  typeFilter,
  setTypeFilter,
  statusFilter,
  setStatusFilter,
  clearFilters,
  onRefresh,
  onAnalyticsToggle,
  showAnalytics = false,
  onExport,
  canExport = false,
  exporting = false,
}: Props) {
  const activeFilters = [
    searchTerm,
    sourceFilter !== 'all' ? sourceFilter : null,
    typeFilter !== 'All' ? typeFilter : null,
    statusFilter !== 'all' ? statusFilter : 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 clients"
            placeholder="Search by company name..."
            className={styles.searchInput}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>

        <div className={styles.toolbarActions}>
          {canExport && onExport && (
            <button
              title="Export the current filtered list to CSV"
              onClick={onExport}
              disabled={exporting}
              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: exporting ? 'wait' : 'pointer',
                opacity: exporting ? 0.7 : 1,
                boxShadow: '0 2px 8px rgba(15,118,110,0.3)',
                whiteSpace: 'nowrap',
                transition: 'transform 0.15s, box-shadow 0.15s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-1px)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              <FiDownload size={16} /> {exporting ? 'Exporting…' : 'Export CSV'}
            </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 0%, #059669 100%)'
                  : 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
                border: 'none',
                borderRadius: 8,
                fontSize: '0.875rem',
                fontWeight: 600,
                cursor: 'pointer',
                boxShadow: showAnalytics
                  ? '0 2px 8px rgba(16,185,129,0.3)'
                  : '0 2px 8px rgba(102,126,234,0.3)',
                whiteSpace: 'nowrap',
                transition: 'transform 0.15s, box-shadow 0.15s',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-1px)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              {showAnalytics ? (
                <>
                  <FiEyeOff size={16} /> Hide Analytics
                </>
              ) : (
                <>
                  <FiBarChart2 size={16} /> Analytics
                </>
              )}
            </button>
          )}

          <button className={styles.btnIcon} title="Print" onClick={() => window.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,
        }}
      >
        <span
          style={{
            fontSize: 11,
            fontWeight: 700,
            color: '#64748b',
            textTransform: 'uppercase',
            letterSpacing: '0.05em',
            marginRight: 4,
          }}
        >
          🔍 Filters:
        </span>

        <select
          className={styles.filterSelect}
          value={sourceFilter}
          onChange={(e) => setSourceFilter(e.target.value as 'all' | ClientSource)}
          style={selectStyle(sourceFilter !== 'all', 140)}
        >
          {SOURCE_OPTIONS.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>

        <select
          className={styles.filterSelect}
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value as ClientTypeFilter)}
          style={selectStyle(typeFilter !== 'All', 160)}
        >
          {TYPE_OPTIONS.map((t) => (
            <option key={t.value} value={t.value}>
              {t.label}
            </option>
          ))}
        </select>

        {/* Status is filtered client-side — the API has no status param yet */}
        <select
          className={styles.filterSelect}
          value={statusFilter}
          onChange={(e) =>
            setStatusFilter(e.target.value as 'all' | 'active' | 'inactive')
          }
          style={selectStyle(statusFilter !== 'all', 150)}
        >
          {STATUS_OPTIONS.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>

        {activeFilters > 0 && (
          <button
            onClick={clearFilters}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 5,
              padding: '7px 14px',
              borderRadius: 8,
              border: '1px solid #fecaca',
              background: '#fef2f2',
              color: '#b91c1c',
              fontSize: 12.5,
              fontWeight: 700,
              cursor: 'pointer',
              marginLeft: 'auto',
            }}
          >
            <FiXCircle size={13} /> Clear ({activeFilters})
          </button>
        )}
      </div>
    </div>
  );
}
