import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ColumnDef } from '@tanstack/react-table';
import { useCompanies, useCompanyExport, useDeleteCompany, Company } from '@/api/hooks';
import { DataGrid } from '@/components/shared/DataGrid';
import { CsvImportDialog } from '@/components/shared/CsvImportDialog';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { EmptyState } from '@/components/ui/EmptyState';
import { ConfirmDialog } from '@/components/ui/ConfirmDialog';
import { useToast } from '@/components/ui/Toast';
import { Badge } from '@/components/ui/Badge';

export function CompaniesListPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const toast = useToast();

  const [page, setPage] = useState(1);
  const [pageSize] = useState(25);
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [importOpen, setImportOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Company | null>(null);

  const { data, isLoading } = useCompanies(page, pageSize, debouncedSearch);
  const exportMutation = useCompanyExport(debouncedSearch);
  const deleteMutation = useDeleteCompany();

  React.useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300);
    return () => clearTimeout(timer);
  }, [search]);

  const columns = useMemo<ColumnDef<Company, any>[]>(
    () => [
      {
        accessorKey: 'name',
        header: t('companies.name'),
        cell: (info) => (
          <span className="font-medium text-primary-700 hover:text-primary-800">
            {info.getValue()}
          </span>
        ),
      },
      {
        accessorKey: 'account_number',
        header: t('companies.accountNumber'),
        cell: (info) => info.getValue() || '—',
      },
      {
        accessorKey: 'industry',
        header: t('companies.industry'),
        cell: (info) =>
          info.getValue() ? (
            <Badge variant="primary">{info.getValue()}</Badge>
          ) : (
            '—'
          ),
      },
      {
        accessorKey: 'phone',
        header: t('companies.phone'),
        cell: (info) => info.getValue() || '—',
      },
      {
        accessorKey: 'email',
        header: t('companies.email'),
        cell: (info) =>
          info.getValue() ? (
            <a href={`mailto:${info.getValue()}`} className="text-primary-600 hover:text-primary-700">
              {info.getValue()}
            </a>
          ) : (
            '—'
          ),
      },
    ],
    [t]
  );

  const handleExport = async () => {
    try {
      const blob = await exportMutation.mutateAsync();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `companies_${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      toast.success(t('companies.export') + ' — OK');
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await deleteMutation.mutateAsync(deleteTarget.id);
      toast.success(t('companies.deleted'));
      setDeleteTarget(null);
    } catch (err: any) {
      toast.error(err.message || t('common.error'));
    }
  };

  const companies = data?.items ?? [];
  const total = data?.total ?? 0;
  const isEmpty = !isLoading && companies.length === 0 && !debouncedSearch;

  if (isEmpty) {
    return (
      <div className="p-6 max-w-7xl mx-auto" data-testid="companies-list-page">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-secondary-900">{t('companies.title')}</h1>
        </div>
        <EmptyState
          title={t('companies.emptyTitle')}
          description={t('companies.emptyDescription')}
          action={
            <Button onClick={() => navigate('/companies/new')}>
              {t('companies.create')}
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div className="p-6 max-w-7xl mx-auto" data-testid="companies-list-page">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-secondary-900">{t('companies.title')}</h1>
        <div className="flex gap-2">
          <Button variant="secondary" onClick={() => setImportOpen(true)}>
            {t('companies.import')}
          </Button>
          <Button
            variant="secondary"
            onClick={handleExport}
            isLoading={exportMutation.isPending}
          >
            {t('companies.export')}
          </Button>
          <Button onClick={() => navigate('/companies/new')}>
            {t('companies.create')}
          </Button>
        </div>
      </div>

      <div className="mb-4">
        <Input
          type="search"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder={t('common.search')}
          aria-label={t('common.search')}
        />
      </div>

      <DataGrid
        columns={columns}
        data={companies}
        total={total}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onRowClick={(row) => navigate(`/companies/${row.id}`)}
        loading={isLoading}
        emptyMessage={t('common.noResults')}
        testId="companies-grid"
      />

      <CsvImportDialog
        open={importOpen}
        onClose={() => setImportOpen(false)}
        onSuccess={() => setPage(1)}
      />

      <ConfirmDialog
        open={!!deleteTarget}
        title={t('companies.deleteConfirmTitle')}
        message={t('companies.deleteConfirm')}
        variant="danger"
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
