'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useLanguage } from '@/lib/language-context';
import { Search } from 'lucide-react';
import React, { useState } from 'react';

interface SearchResult {
  _id: string;
  firstName: string;
  lastName: string;
  email: string;
  [key: string]: any;
}

export default function SearchEngine() {
  const { t, language } = useLanguage();
  const [searchTerm, setSearchTerm] = useState('');
  const [searchType, setSearchType] = useState('name');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);

  const getLocalizedGender = (gender?: string) => {
    if (!gender) return t('common.na');
    const normalized = gender.trim().toLowerCase();
    if (normalized === 'male') return t('common.male');
    if (normalized === 'female') return t('common.female');
    if (normalized === 'other') return t('common.other');
    return gender;
  };

  const handleSearch = async (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!searchTerm.trim()) {
      setResults([]);
      return;
    }

    setLoading(true);
    setSearched(true);

    try {
      // Search patients by name, date, or diagnosis
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/patients`);
      const data = await response.json();

      if (data.success) {
        let filtered = data.data;

        // Filter based on search type
        if (searchType === 'name') {
          filtered = filtered.filter((patient: any) =>
            `${patient.userId.firstName} ${patient.userId.lastName}`
              .toLowerCase()
              .includes(searchTerm.toLowerCase())
          );
        } else if (searchType === 'email') {
          filtered = filtered.filter((patient: any) =>
            patient.userId.email.toLowerCase().includes(searchTerm.toLowerCase())
          );
        } else if (searchType === 'phone') {
          filtered = filtered.filter((patient: any) =>
            patient.userId.phone?.includes(searchTerm)
          );
        }

        setResults(filtered);
      }
    } catch (error) {
      console.error('Error searching:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-3xl font-bold">{t('searchPage.title')}</h2>
        <p className="text-gray-600 mt-1">{t('searchPage.description')}</p>
      </div>

      {/* Search Form */}
      <form onSubmit={handleSearch} className="bg-white p-6 rounded-lg border shadow-sm">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <Label htmlFor="searchType">{t('searchPage.searchBy')}</Label>
            <Select value={searchType} onValueChange={setSearchType}>
              <SelectTrigger className="h-12">
                <SelectValue placeholder={t('doctors.searchPlaceholder')} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="name">{t('common.name')}</SelectItem>
                <SelectItem value="email">{t('common.email')}</SelectItem>
                <SelectItem value="phone">{t('common.phone')}</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="md:col-span-2">
            <Label htmlFor="searchTerm">{t('searchPage.searchTerm')}</Label>
            <Input
              id="searchTerm"
              placeholder={`${t('searchPage.enter')} ${searchType === 'name' ? t('common.name') : searchType === 'email' ? t('common.email') : t('common.phone')}...`}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="h-12"
            />
          </div>

          <div className="flex items-end">
            <Button type="submit" disabled={loading} className="w-full h-12 gap-2">
              <Search className="h-4 w-4" />
              {loading ? t('searchPage.searching') : t('searchPage.searchButton')}
            </Button>
          </div>
        </div>
      </form>

      {/* Results */}
      {searched && (
        <div className="bg-white rounded-lg border">
          {results.length > 0 ? (
            <>
              <div className="px-6 py-4 border-b">
                <p className="text-sm text-gray-600">
                  {t('searchPage.foundPatients')} <strong>{results.length}</strong> {t('searchPage.patientsSuffix')}
                </p>
              </div>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t('common.name')}</TableHead>
                    <TableHead>{t('common.email')}</TableHead>
                    <TableHead>{t('common.phone')}</TableHead>
                    <TableHead>{t('common.gender')}</TableHead>
                    <TableHead>{t('common.dateOfBirth')}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {results.map((patient) => (
                    <TableRow key={patient._id}>
                      <TableCell className="font-medium">
                        {patient.userId.firstName} {patient.userId.lastName}
                      </TableCell>
                      <TableCell>{patient.userId.email}</TableCell>
                      <TableCell>{patient.userId.phone || t('common.na')}</TableCell>
                      <TableCell>{getLocalizedGender(patient.gender)}</TableCell>
                      <TableCell>
                        {patient.dateOfBirth
                          ? new Date(patient.dateOfBirth).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US', { timeZone: 'UTC' })
                          : t('common.na')}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </>
          ) : (
            <div className="px-6 py-12 text-center">
              <p className="text-gray-500">{t('searchPage.noPatientsFound')}</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
