'use client';

import React from 'react';
import {
  FiSearch,
  FiX,
  FiRefreshCw,
  FiFilter,
  FiCalendar,
  FiUser,
} from 'react-icons/fi';
import { TOKENS } from './fc.tokens';

export type FcSourceFilter = 'all' | 'QRS' | 'TQS' | 'NEW';
export type FcNcTypeFilter = 'all' | 'Major' | 'Minor' | 'Observation';

export interface FcUserOption {
  name: string;
  count?: number;
}

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

  sourceFilter: FcSourceFilter;
  setSourceFilter: (v: FcSourceFilter) => void;

  ncTypeFilter: FcNcTypeFilter;
  setNcTypeFilter: (v: FcNcTypeFilter) => void;

  auditTypeFilter: string;
  setAuditTypeFilter: (v: string) => void;

  userFilter: string;
  setUserFilter: (v: string) => void;
  availableUsers: FcUserOption[];

  dateFrom: string;
  setDateFrom: (v: string) => void;
  dateTo: string;
  setDateTo: (v: string) => void;

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

export default function FinalClosureFilters({
  searchTerm,
  setSearchTerm,
  sourceFilter,
  setSourceFilter,
  ncTypeFilter,
  setNcTypeFilter,
  auditTypeFilter,
  setAuditTypeFilter,
  userFilter,
  setUserFilter,
  availableUsers,
  dateFrom,
  setDateFrom,
  dateTo,
  setDateTo,
  clearFilters,
  onRefresh,
}: Props) {
  const activeCount =
    (searchTerm ? 1 : 0) +
    (sourceFilter !== 'all' ? 1 : 0) +
    (ncTypeFilter !== 'all' ? 1 : 0) +
    (auditTypeFilter !== 'all' ? 1 : 0) +
    (userFilter !== 'all' ? 1 : 0) +
    (dateFrom ? 1 : 0) +
    (dateTo ? 1 : 0);

  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: 12,
        padding: 16,
        marginBottom: 14,
        display: 'flex',
        flexDirection: 'column',
        gap: 14,
        boxShadow:
          '0 1px 2px rgba(15,23,42,0.04), 0 4px 12px rgba(15,23,42,0.04)',
      }}
    >
      {/* ─── Top row: search + refresh ─── */}
      <div
        style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}
      >
        <div style={{ position: 'relative', flex: '1 1 320px', minWidth: 280 }}>
          <FiSearch
            size={14}
            strokeWidth={2.2}
            style={{
              position: 'absolute',
              left: 13,
              top: '50%',
              transform: 'translateY(-50%)',
              color: TOKENS.ink5,
              pointerEvents: 'none',
            }}
          />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search by company, auditor, NC id…"
            style={{
              width: '100%',
              background: TOKENS.bg,
              border: `1px solid ${searchTerm ? TOKENS.brand : TOKENS.line}`,
              borderRadius: 9,
              padding: '10px 36px 10px 38px',
              fontSize: 13,
              fontWeight: 500,
              color: TOKENS.ink,
              height: 40,
              outline: 'none',
              transition: 'all 0.15s',
            }}
            onFocus={(e) => {
              e.currentTarget.style.background = TOKENS.surface;
              e.currentTarget.style.borderColor = TOKENS.brand;
              e.currentTarget.style.boxShadow = '0 0 0 3px rgba(15,118,110,0.10)';
            }}
            onBlur={(e) => {
              e.currentTarget.style.background = TOKENS.bg;
              e.currentTarget.style.borderColor = searchTerm
                ? TOKENS.brand
                : TOKENS.line;
              e.currentTarget.style.boxShadow = 'none';
            }}
          />
          {searchTerm && (
            <button
              onClick={() => setSearchTerm('')}
              aria-label="Clear search"
              style={{
                position: 'absolute',
                right: 10,
                top: '50%',
                transform: 'translateY(-50%)',
                background: TOKENS.line,
                border: 'none',
                cursor: 'pointer',
                padding: 0,
                width: 18,
                height: 18,
                borderRadius: 9,
                color: TOKENS.ink3,
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <FiX size={11} strokeWidth={2.5} />
            </button>
          )}
        </div>

        <button
          onClick={onRefresh}
          title="Refresh"
          aria-label="Refresh"
          style={{
            width: 40,
            height: 40,
            background: TOKENS.surface,
            border: `1px solid ${TOKENS.line}`,
            borderRadius: 9,
            cursor: 'pointer',
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: TOKENS.ink3,
            transition: 'all 0.15s',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = TOKENS.bg;
            e.currentTarget.style.borderColor = TOKENS.ink5;
            e.currentTarget.style.color = TOKENS.ink;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = TOKENS.surface;
            e.currentTarget.style.borderColor = TOKENS.line;
            e.currentTarget.style.color = TOKENS.ink3;
          }}
        >
          <FiRefreshCw size={14} strokeWidth={2.2} />
        </button>
      </div>

      {/* ─── Bottom row: filter selects ─── */}
      <div
        style={{
          display: 'flex',
          gap: 10,
          alignItems: 'center',
          flexWrap: 'wrap',
          paddingTop: 12,
          borderTop: `1px solid ${TOKENS.line2}`,
        }}
      >
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 6,
            fontSize: 11,
            fontWeight: 800,
            letterSpacing: '0.08em',
            textTransform: 'uppercase',
            color: TOKENS.brand,
            marginRight: 4,
          }}
        >
          <FiFilter size={12} strokeWidth={2.4} />
          Filters
          {activeCount > 0 && (
            <span
              style={{
                background: TOKENS.brand,
                color: '#fff',
                fontSize: 9,
                fontWeight: 800,
                padding: '1px 6px',
                borderRadius: 99,
                letterSpacing: 0,
              }}
            >
              {activeCount}
            </span>
          )}
        </span>

        <FilterSelect
          value={sourceFilter}
          onChange={(v) => setSourceFilter(v as FcSourceFilter)}
          options={[
            { value: 'all', label: 'All Sources' },
            { value: 'QRS', label: 'QRS only' },
            { value: 'TQS', label: 'TQS only' },
            { value: 'NEW', label: 'New (QRS|TQS)' },
          ]}
        />

        <FilterSelect
          value={ncTypeFilter}
          onChange={(v) => setNcTypeFilter(v as FcNcTypeFilter)}
          options={[
            { value: 'all', label: 'All NC Types' },
            { value: 'Major', label: 'Major' },
            { value: 'Minor', label: 'Minor' },
            { value: 'Observation', label: 'Observation' },
          ]}
        />

        <FilterSelect
          value={auditTypeFilter}
          onChange={(v) => setAuditTypeFilter(v)}
          options={[
            { value: 'all', label: 'All Audit Types' },
            { value: 'initial audit', label: 'Initial Audit' },
            { value: 'surveillance(No. 01)', label: 'Surveillance (No. 01)' },
            { value: 'surveillance(No. 02)', label: 'Surveillance (No. 02)' },
            { value: 'Re-Assessment', label: 'Re-Assessment' },
          ]}
        />

        <UserFilterSelect
          value={userFilter}
          onChange={setUserFilter}
          users={availableUsers}
        />

        <DateInput label="From" value={dateFrom} onChange={setDateFrom} />
        <DateInput label="To" value={dateTo} onChange={setDateTo} />

        {activeCount > 0 && (
          <button
            onClick={clearFilters}
            style={{
              marginLeft: 'auto',
              padding: '7px 12px',
              background: '#fef2f2',
              border: '1px solid #fecaca',
              borderRadius: 7,
              cursor: 'pointer',
              fontSize: 11,
              fontWeight: 700,
              color: TOKENS.danger,
              height: 34,
              display: 'inline-flex',
              alignItems: 'center',
              gap: 5,
              transition: 'all 0.15s',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = '#fee2e2';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = '#fef2f2';
            }}
          >
            <FiX size={11} strokeWidth={2.5} />
            Clear filters
          </button>
        )}
      </div>
    </div>
  );
}

// ─── Sub-components ─────────────────────────────────────────────────

function FilterSelect({
  value,
  onChange,
  options,
}: {
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      style={{
        appearance: 'none',
        WebkitAppearance: 'none',
        MozAppearance: 'none',
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: 7,
        padding: '7px 28px 7px 12px',
        fontSize: 12,
        fontWeight: 600,
        color: TOKENS.ink2,
        cursor: 'pointer',
        height: 34,
        outline: 'none',
        backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>")`,
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'right 8px center',
        transition: 'all 0.15s',
      }}
    >
      {options.map((opt) => (
        <option key={opt.value} value={opt.value}>
          {opt.label}
        </option>
      ))}
    </select>
  );
}

function UserFilterSelect({
  value,
  onChange,
  users,
}: {
  value: string;
  onChange: (v: string) => void;
  users: FcUserOption[];
}) {
  return (
    <div
      style={{ position: 'relative', display: 'inline-flex', alignItems: 'center' }}
    >
      <FiUser
        size={11}
        strokeWidth={2.4}
        style={{
          position: 'absolute',
          left: 9,
          top: '50%',
          transform: 'translateY(-50%)',
          color: TOKENS.ink4,
          pointerEvents: 'none',
        }}
      />
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          appearance: 'none',
          WebkitAppearance: 'none',
          MozAppearance: 'none',
          background: TOKENS.surface,
          border: `1px solid ${TOKENS.line}`,
          borderRadius: 7,
          padding: '7px 28px 7px 26px',
          fontSize: 12,
          fontWeight: 600,
          color: TOKENS.ink2,
          cursor: 'pointer',
          height: 34,
          outline: 'none',
          maxWidth: 200,
          backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>")`,
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'right 8px center',
          textOverflow: 'ellipsis',
          transition: 'all 0.15s',
        }}
      >
        <option value="all">
          All Users{users.length > 0 ? ` (${users.length})` : ''}
        </option>
        {users.map((u) => (
          <option key={u.name} value={u.name}>
            {u.name}
            {u.count !== undefined ? ` (${u.count})` : ''}
          </option>
        ))}
      </select>
    </div>
  );
}

function DateInput({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <label
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 6,
        fontSize: 11,
        color: TOKENS.ink3,
        fontWeight: 700,
        letterSpacing: '0.02em',
      }}
    >
      <FiCalendar size={11} strokeWidth={2.4} color={TOKENS.ink4} />
      {label}:
      <input
        type="date"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          background: TOKENS.surface,
          border: `1px solid ${TOKENS.line}`,
          borderRadius: 7,
          padding: '6px 10px',
          fontSize: 12,
          fontWeight: 600,
          color: TOKENS.ink2,
          cursor: 'pointer',
          height: 34,
          outline: 'none',
          fontFamily: 'inherit',
          transition: 'all 0.15s',
        }}
      />
    </label>
  );
}
