'use client';
import { useEffect, useState } from 'react';
import { Save, CheckCircle2 } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { storeService } from '@/services/store.service';
import { Card, CardHeader, CardBody } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Textarea } from '@/components/ui/Textarea';
import { Button } from '@/components/ui/Button';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState } from '@/components/ui/States';
import type { Store } from '@/types';

export default function ConfiguracoesPage() {
  const { storeId } = useAuth();
  const { data, loading } = useApi(
    () => (storeId ? storeService.getById(storeId) : Promise.resolve(null)),
    [storeId],
  );
  const [form, setForm] = useState<Store | null>(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => { if (data) setForm(data); }, [data]);

  if (loading || !form) return <LoadingState />;

  function set<K extends keyof Store>(key: K, value: Store[K]) {
    setForm((f) => (f ? { ...f, [key]: value } : f));
  }
  function setSocial(key: keyof Store['social'], value: string) {
    setForm((f) => (f ? { ...f, social: { ...f.social, [key]: value } } : f));
  }
  function setPolicy(key: keyof Store['policies'], value: string) {
    setForm((f) => (f ? { ...f, policies: { ...f.policies, [key]: value } } : f));
  }
  async function save() {
    if (!form || !storeId) return;
    await storeService.updateSettings(storeId, form);
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  }

  return (
    <>
      <PageHeader
        title="Configurações da loja"
        subtitle="Dados, contato e políticas"
        action={
          <Button onClick={save}>
            {saved ? <><CheckCircle2 className="h-4 w-4" /> Salvo</> : <><Save className="h-4 w-4" /> Salvar</>}
          </Button>
        }
      />
      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader title="Dados gerais" />
          <CardBody className="space-y-4">
            <Input label="Nome da loja" value={form.name} onChange={(e) => set('name', e.target.value)} />
            <Input label="Slug (link público)" value={form.slug} onChange={(e) => set('slug', e.target.value)} />
            <Textarea label="Descrição" rows={2} value={form.description} onChange={(e) => set('description', e.target.value)} />
            <Input label="CNPJ/CPF" value={form.document} onChange={(e) => set('document', e.target.value)} />
            <Input label="Endereço" value={form.address} onChange={(e) => set('address', e.target.value)} />
            <label className="flex items-center gap-2 text-sm text-ink-700">
              <input type="checkbox" checked={form.open} onChange={(e) => set('open', e.target.checked)} />
              Loja aberta (recebendo pedidos)
            </label>
          </CardBody>
        </Card>

        <Card>
          <CardHeader title="Contato e redes" />
          <CardBody className="space-y-4">
            <Input label="E-mail" value={form.email} onChange={(e) => set('email', e.target.value)} />
            <Input label="Telefone" value={form.phone} onChange={(e) => set('phone', e.target.value)} />
            <Input label="WhatsApp (só números, com DDI)" value={form.social.whatsapp ?? ''} onChange={(e) => setSocial('whatsapp', e.target.value)} placeholder="5511999990000" />
            <Input label="Instagram" value={form.social.instagram ?? ''} onChange={(e) => setSocial('instagram', e.target.value)} />
            <Input label="Facebook" value={form.social.facebook ?? ''} onChange={(e) => setSocial('facebook', e.target.value)} />
          </CardBody>
        </Card>

        <Card className="lg:col-span-2">
          <CardHeader title="Políticas" />
          <CardBody className="grid gap-4 sm:grid-cols-2">
            <Textarea label="Política de entrega" rows={3} value={form.policies.shipping ?? ''} onChange={(e) => setPolicy('shipping', e.target.value)} />
            <Textarea label="Política de troca" rows={3} value={form.policies.exchange ?? ''} onChange={(e) => setPolicy('exchange', e.target.value)} />
            <Textarea label="Política de privacidade" rows={3} value={form.policies.privacy ?? ''} onChange={(e) => setPolicy('privacy', e.target.value)} />
            <Textarea label="Termos de compra" rows={3} value={form.policies.terms ?? ''} onChange={(e) => setPolicy('terms', e.target.value)} />
          </CardBody>
        </Card>
      </div>
    </>
  );
}
