import React, { useRef, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Sun, Moon, Laptop, Save, Trash2, Upload, FlaskConical, Download, FolderOpen, FileBox, FileJson } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useTheme } from '@/lib/theme';
import { useProjects } from '@/lib/hooks/useProjects';
import { useWindStore } from '@/store/appStore';
import { useHydrationStore } from '@/store/hydrationStore';
import { useI18n } from '@/store/i18nStore';
import { Badge } from '@/components/ui/badge';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  importProjectFromText,
  readProjectFile,
} from '@/lib/import-project';
import AuditPanel from '@/components/AuditPanel';
import Glossary from '@/components/Glossary';

const SettingsModule: React.FC = () => {
  const { theme, setTheme, effectiveTheme } = useTheme();
  const { projects, loading, error, remove, save } = useProjects();
  const { t, locale } = useI18n();
  const navigate = useNavigate();
  const location = useLocation();
  const setPendingLoad = useHydrationStore((s) => s.setPendingLoad);

  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const logoInputRef = useRef<HTMLInputElement | null>(null);
  const [importing, setImporting] = useState(false);
  const { companyLogo, setCompanyLogo } = useWindStore();

  const exportSnapshot = () => {
    const state = useWindStore.getState();
    const blob = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', 'ventoapp-snapshot.json');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleDownloadJSON = (project: any) => {
    const blob = new Blob([JSON.stringify(project, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `${project.name}.json`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleLoadProject = (project: any) => {
    if (project.type === 'projeto' && project.windData) {
      // Restore wind data
      useWindStore.setState(project.windData);
    }
    
    // Set pending load
    setPendingLoad(project.module, project.inputs);
    
    // Navigate to module
    navigate(`/${project.module === 'isolated-roof' ? 'cobertura-isolada' : project.module === 'sign' ? 'muros' : project.module === 'bar' ? 'barras' : project.module === 'bridge' ? 'pontes' : project.module === 'dynamics' ? 'dinamica' : project.module === 'vault' ? 'abobada' : project.module === 'dome' ? 'cupula' : project.module}`);
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileSelected = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    setImporting(true);
    try {
      const text = await readProjectFile(file);
      const parsed = JSON.parse(text);
      if (parsed.module && parsed.inputs) {
        // Formato SavedProject (Projeto ou Template)
        const newProject = {
          ...parsed,
          name: parsed.name || 'Importado - ' + file.name,
          type: parsed.type || 'projeto',
          createdAt: Date.now(),
          updatedAt: Date.now(),
        };
        // Ensure type is correct
        if (!['projeto', 'template'].includes(newProject.type)) newProject.type = 'projeto';
        
        await save(newProject as any);
      } else {
        // Old snapshot import fallback
        importProjectFromText(text);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setImporting(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const currentTab = new URLSearchParams(location.search).get('tab') || 'config';
  const isSettingsGroup = currentTab === 'config' || currentTab === 'testes';

  return (
    <div className="p-6 max-w-5xl mx-auto overflow-auto">
      <h1 className="text-3xl font-bold mb-6">
        {currentTab === 'gerenciador' ? 'Arquivos' : 
         currentTab === 'glossary' ? 'Glossário' : 
         'Configurações'}
      </h1>

      <Tabs value={currentTab} onValueChange={(val) => navigate(`/settings?tab=${val}`)} className="w-full">
        {isSettingsGroup && (
          <TabsList className="grid w-full mb-6 grid-cols-2">
            <TabsTrigger value="config">Preferências</TabsTrigger>
            <TabsTrigger value="testes">
              <FlaskConical className="w-4 h-4 mr-1.5" />
              Testes
            </TabsTrigger>
          </TabsList>
        )}

        <TabsContent value="config" className="space-y-6">

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t('settings_appearance')}</CardTitle>
          <CardDescription>{t('settings_appearance_desc')}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-3 gap-1 sm:gap-2 w-full sm:w-fit sm:flex">
            <Button variant={theme === 'light' ? 'default' : 'outline'} className="text-xs sm:text-sm px-1 sm:px-4 h-8 sm:h-9" onClick={() => setTheme('light')}>
              <Sun className="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1 sm:mr-2 shrink-0" /> {t('settings_theme_light')}
            </Button>
            <Button variant={theme === 'dark' ? 'default' : 'outline'} className="text-xs sm:text-sm px-1 sm:px-4 h-8 sm:h-9" onClick={() => setTheme('dark')}>
              <Moon className="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1 sm:mr-2 shrink-0" /> {t('settings_theme_dark')}
            </Button>
            <Button variant={theme === 'system' ? 'default' : 'outline'} className="text-xs sm:text-sm px-1 sm:px-4 h-8 sm:h-9" onClick={() => setTheme('system')}>
              <Laptop className="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1 sm:mr-2 shrink-0" /> {t('settings_theme_system')}
            </Button>
          </div>
          <p className="text-xs text-muted-foreground mt-3">
            {t('settings_effective')}: <Badge variant="outline">{effectiveTheme}</Badge>
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Logotipo da Empresa</CardTitle>
          <CardDescription>Insira o logotipo da sua empresa para aparecer no cabeçalho esquerdo dos relatórios PDF exportados.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col sm:flex-row items-center gap-6">
            <div className="w-40 h-24 border-2 border-dashed border-border rounded-lg flex items-center justify-center bg-muted/20 overflow-hidden relative">
              {companyLogo ? (
                <img src={companyLogo} alt="Logo da Empresa" className="w-full h-full object-contain p-2" />
              ) : (
                <span className="text-xs text-muted-foreground text-center p-2">Sem logotipo</span>
              )}
            </div>
            <div className="flex flex-col gap-2 w-full sm:w-auto">
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => logoInputRef.current?.click()} className="text-xs">
                  <Upload className="w-3.5 h-3.5 mr-1.5" />
                  Carregar Logo
                </Button>
                {companyLogo && (
                  <Button variant="destructive" size="sm" onClick={() => setCompanyLogo(null)} className="text-xs">
                    <Trash2 className="w-3.5 h-3.5 mr-1.5" />
                    Excluir
                  </Button>
                )}
              </div>
              <p className="text-[11px] text-muted-foreground">
                Formatos aceitos: PNG, JPG, SVG. Tamanho recomendado: proporção retangular (ex: 4:3 ou 16:9).
              </p>
            </div>
          </div>
          <input
            type="file"
            ref={logoInputRef}
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (!file) return;
              const reader = new FileReader();
              reader.onload = (event) => {
                if (typeof event.target?.result === 'string') {
                  setCompanyLogo(event.target.result);
                }
              };
              reader.readAsDataURL(file);
            }}
            className="hidden"
            accept="image/*"
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t('settings_about')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-sm">
          <p><strong>{t('app_title')}</strong> — {t('settings_about_desc')}</p>
          <p className="text-muted-foreground">
            {t('settings_stack')}: React 19 + TypeScript + Vite + Tailwind v4 + shadcn/ui + Zustand + R3F + @react-pdf/renderer.
          </p>
          <p className="text-muted-foreground">
            Cobertura: 11 seções normativas + 3 anexos. Todos os 8 marcos do plano de implementação concluídos.
          </p>
          <p className="text-[10px] text-muted-foreground/60 mt-3 pt-2 border-t border-border/50 italic">
            Desenvolvido por BrainSteel do Brasil - resp. Eng. Marcos A. Reifonas
          </p>
        </CardContent>
      </Card>
        </TabsContent>

        <TabsContent value="gerenciador" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Arquivos (Gerenciador)</CardTitle>
              <CardDescription>Gerencie seus Projetos Completos e Templates de geometria salvos localmente.</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between mb-4 gap-2 flex-wrap">
                <p className="text-sm text-muted-foreground">
                  {projects.length} arquivo(s) armazenado(s).
                </p>
                <div className="grid grid-cols-2 gap-1.5 w-full sm:w-auto sm:flex">
                  <Button size="sm" variant="outline" className="text-xs px-2 h-8 flex-1 sm:flex-none" onClick={handleImportClick} disabled={importing}>
                    <Upload className="w-3.5 h-3.5 mr-1.5 shrink-0" /> Importar Arquivo
                  </Button>
                  <Button size="sm" variant="outline" className="text-xs px-2 h-8 flex-1 sm:flex-none" onClick={exportSnapshot}>
                    <Save className="w-3.5 h-3.5 mr-1.5 shrink-0" /> Exportar Wind Snapshot
                  </Button>
                </div>
              </div>

              {loading && <p className="text-sm text-muted-foreground">{t('common_loading')}</p>}
              {error && <p className="text-sm text-destructive">{error}</p>}
              {projects.length === 0 && !loading && (
                <p className="text-sm text-muted-foreground">Nenhum projeto ou template salvo ainda.</p>
              )}
              <div className="space-y-2">
                {projects.map((p) => (
                  <div key={p.id} className="flex items-center justify-between p-3 border rounded-md hover:bg-muted/40 transition-colors">
                    <div className="flex items-center gap-3">
                      {p.type === 'projeto' ? (
                        <div className="p-2 bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 rounded-md">
                          <FileBox className="w-5 h-5" />
                        </div>
                      ) : (
                        <div className="p-2 bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400 rounded-md">
                          <FileJson className="w-5 h-5" />
                        </div>
                      )}
                      <div>
                        <div className="font-medium text-sm flex items-center gap-2">
                          {p.name}
                          <Badge variant="outline" className="text-[10px] px-1 py-0 h-4">
                            {p.module}
                          </Badge>
                        </div>
                        <div className="text-xs text-muted-foreground mt-0.5">
                          {p.type === 'projeto' ? 'Projeto (Vento + Geometria)' : 'Template (Apenas Geometria)'} · {new Date(p.updatedAt).toLocaleString(locale === 'pt-BR' ? 'pt-BR' : 'en-US')}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-1">
                      <Button size="sm" variant="ghost" title="Carregar" className="h-8 w-8 p-0 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50 dark:text-emerald-400 dark:hover:bg-emerald-950/50" onClick={() => handleLoadProject(p)}>
                        <FolderOpen className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="ghost" title="Baixar JSON" className="h-8 w-8 p-0" onClick={() => handleDownloadJSON(p)}>
                        <Download className="w-4 h-4" />
                      </Button>
                      <Button size="sm" variant="ghost" title="Excluir" className="h-8 w-8 p-0 text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-950/50" onClick={() => p.id && remove(p.id)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="glossary" className="space-y-6">
          <Glossary />
        </TabsContent>

        <TabsContent value="testes" className="space-y-6">
          <AuditPanel />
        </TabsContent>
      </Tabs>
      <input type="file" ref={fileInputRef} onChange={handleFileSelected} className="hidden" accept=".json" />
    </div>
  );
};

export default SettingsModule;