'use client';

import { useEffect, useState, useMemo } from 'react';
import Link from 'next/link';

export default function LaserSourcesPage() {
  const [sources, setSources] = useState([]);
  const [query, setQuery] = useState('');
  const [debouncedQuery, setDebouncedQuery] = useState('');
  const [wavelengthFilters, setWavelengthFilters] = useState<Record<string, number | null>>({});
  const [sortKey, setSortKey] = useState('model');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedQuery(query), 300);
    return () => clearTimeout(timer);
  }, [query]);

  useEffect(() => {
    fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/items/laser_source?limit=-1&fields=*,op.label`)
      .then((res) => res.json())
      .then((data) => setSources(data.data || []));
  }, []);

  const highlightMatch = (text: string, query: string) => {
    if (!query || !text) return text;
    const parts = text.split(new RegExp(`(${query})`, 'gi'));
    return parts.map((part, i) =>
      part.toLowerCase() === query.toLowerCase() ? <mark key={i}>{part}</mark> : part
    );
  };

  const filtered = useMemo(() => {
    const q = debouncedQuery.toLowerCase();
    return sources.filter((src) => {
      const matchesQuery = [src.make, src.model].filter(Boolean).some((field) =>
        field.toLowerCase().includes(q)
      );
      return matchesQuery;
    });
  }, [sources, debouncedQuery]);

  const grouped = useMemo<Record<string, typeof filtered>>(() => {
    return filtered.reduce((acc, src) => {
      const key = src.make || 'Unknown Make';
      acc[key] = acc[key] || [];
      acc[key].push(src);
      return acc;
    }, {} as Record<string, typeof filtered>);
  }, [filtered]);

  const wavelengths = [10600, 1064, 455, 355];

  const toggleFilter = (make: string, value: number) => {
    setWavelengthFilters((prev) => ({
      ...prev,
      [make]: prev[make] === value ? null : value
    }));
  };

  const toggleSort = (key: string) => {
    setSortKey(key);
    setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'));
  };

  const getSortableValue = (val: any, key: string) => {
    if (!val) return '';
    if (key === 'w') return parseFloat(val.replace(/[^\d.]/g, '')) || 0;
    if (['mj', 'nm', 'khz', 'ns', 'v'].includes(key.toLowerCase())) return parseFloat(val) || 0;
    return val.toString().toLowerCase();
  };

  const sortArrow = (key: string) =>
    sortKey === key ? (sortOrder === 'asc' ? ' ▲' : ' ▼') : '';

  const summaryStats = useMemo(() => {
    const makes = new Set();
    const nmCounts: Record<string, number> = {};
    for (const src of sources) {
      if (src.make) makes.add(src.make);
      if (src.nm) {
        const nm = src.nm;
        nmCounts[nm] = (nmCounts[nm] || 0) + 1;
      }
    }
    const mostCommonNm = Object.entries(nmCounts)
      .sort((a, b) => (Number(b[1]) || 0) - (Number(a[1]) || 0))[0]?.[0] || '—';
    return {
      total: sources.length,
      uniqueMakes: makes.size,
      commonNm: mostCommonNm,
    };
  }, [sources]);

  const recentSources = useMemo(() => {
    return [...sources]
      .filter((src) => src.submission_id)
      .sort((a, b) => b.submission_id - a.submission_id)
      .slice(0, 5);
  }, [sources]);

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="grid gap-4 md:grid-cols-3 mb-6">
        <div className="card p-4">
          <h2 className="text-lg font-semibold mb-2">Database Summary</h2>
          <p>Total Sources: {summaryStats.total}</p>
          <p>Unique Makes: {summaryStats.uniqueMakes}</p>
          <p>Most Common Wavelength: {summaryStats.commonNm}</p>
        </div>

        <div className="card p-4">
          <h2 className="text-lg font-semibold mb-2">Recent Additions</h2>
          <ul className="text-sm list-disc pl-4">
            {recentSources.map((src) => (
              <li key={src.id}>
                <Link className="text-accent underline" href={`/lasers/${src.submission_id}`}>
                  {src.make} {src.model}
                </Link>
              </li>
            ))}
          </ul>
        </div>

        <div className="card p-4">
          <h2 className="text-lg font-semibold mb-2">Feedback</h2>
          <p className="text-sm mb-2">See something wrong or want to suggest an improvement?</p>
          <Link href="#" className="btn-primary inline-block">Submit Feedback</Link>
        </div>
      </div>

      <div className="mb-6 card bg-card text-card-foreground">
        <h1 className="text-3xl font-bold mb-2">Laser Source Database</h1>
        <input
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search by make or model..."
          className="w-full max-w-md mb-4 dark:bg-background border border-border rounded-md p-2"
        />
        <p className="text-sm text-muted-foreground">
          Browse laser source specifications collected from community-submitted and verified sources.
        </p>
      </div>

      {Object.entries(grouped).length === 0 ? (
        <p className="text-muted">No laser sources found.</p>
      ) : (
        <div className="space-y-6">
          {Object.entries(grouped).map(([make, items]) => {
            const filteredItems = wavelengthFilters[make] != null
              ? items.filter(item => parseInt(item.nm) === wavelengthFilters[make])
              : items;

            const sortedItems = [...filteredItems].sort((a, b) => {
              const aVal = getSortableValue(a[sortKey], sortKey);
              const bVal = getSortableValue(b[sortKey], sortKey);
              if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;
              if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;
              return 0;
            });

            return (
              <details key={make} className="border border-border rounded-md">
                <summary className="bg-card px-4 py-2 font-semibold cursor-pointer flex justify-between items-center">
                  <span>{make} <span className="text-sm text-muted">({filteredItems.length})</span></span>
                  <div className="space-x-2">
                    {wavelengths.map((w) => (
                      <button
                        key={w}
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleFilter(make, w);
                        }}
                        className={`px-2 py-1 text-xs rounded-md border ${wavelengthFilters[make] === w ? 'bg-accent text-white' : 'bg-muted text-muted-foreground'}`}
                      >
                        {w}
                      </button>
                    ))}
                  </div>
                </summary>
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[900px] text-sm whitespace-nowrap">
                    <thead>
                      <tr>
                        <th className="px-2 py-2 text-left">Make</th>
                        <th className="px-2 py-2 text-left w-64">
                          <button onClick={() => toggleSort('model')}>Model{sortArrow('model')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('w')}>W{sortArrow('w')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('mj')}>mJ{sortArrow('mj')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('op')}>OP{sortArrow('op')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('nm')}>nm{sortArrow('nm')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('kHz')}>kHz{sortArrow('kHz')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('ns')}>ns{sortArrow('ns')}</button>
                        </th>
                        <th className="px-2 py-2 text-left">
                          <button onClick={() => toggleSort('v')}>V{sortArrow('v')}</button>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {sortedItems.map((src) => (
                        <tr key={src.id} className="border-t border-border">
                          <td className="px-2 py-2 truncate max-w-[10rem]">{highlightMatch(src.make || '—', debouncedQuery)}</td>
                          <td className="px-2 py-2 truncate max-w-[16rem]">
                            <Link href={`/lasers/${src.submission_id}`} className="text-accent underline">
                              {highlightMatch(src.model || '—', debouncedQuery)}
                            </Link>
                          </td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.w || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.mj || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.op?.label || src.op || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.nm || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.kHz || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.ns || '—'}</td>
                          <td className="px-2 py-2 whitespace-nowrap">{src.v || '—'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </details>
            );
          })}
        </div>
      )}
    </div>
  );
}

