import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import { Link } from "wouter";
import { Loader2, Upload, Camera, CheckCircle2 } from "lucide-react";

export default function Home() {
  const [selectedJobId, setSelectedJobId] = useState<string>("");
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [rgFront, setRgFront] = useState<File | null>(null);
  const [rgBack, setRgBack] = useState<File | null>(null);
  const [rgFrontPreview, setRgFrontPreview] = useState<string>("");
  const [rgBackPreview, setRgBackPreview] = useState<string>("");
  const [consentimento, setConsentimento] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const jobsQuery = trpc.jobs.list.useQuery();
  const createAppMutation = trpc.applications.create.useMutation();

  const handleFileChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    isBack: boolean
  ) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 5 * 1024 * 1024) {
        toast.error("Arquivo muito grande. Máximo 5MB.");
        return;
      }
      if (!["image/jpeg", "image/png", "application/pdf"].includes(file.type)) {
        toast.error("Formato inválido. Aceitos: JPG, PNG ou PDF.");
        return;
      }

      const reader = new FileReader();
      reader.onload = (event) => {
        const preview = event.target?.result as string;
        if (isBack) {
          setRgBack(file);
          setRgBackPreview(preview);
        } else {
          setRgFront(file);
          setRgFrontPreview(preview);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCameraCapture = (isBack: boolean) => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.capture = "environment";
    input.onchange = (e) => handleFileChange(e as any, isBack);
    input.click();
  };

  const uploadFileToStorage = async (file: File, prefix: string): Promise<string> => {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("prefix", prefix);

    const response = await fetch("/api/upload", {
      method: "POST",
      body: formData,
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || "Erro ao fazer upload do arquivo");
    }

    const data = await response.json();
    return data.url;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedJobId || !fullName || !phone || !rgFront || !rgBack || !consentimento) {
      toast.error("Preencha todos os campos obrigatórios.");
      return;
    }

    setIsSubmitting(true);

    try {
      toast.loading("Enviando candidatura...");

      // Upload files to S3
      const rgFrontUrl = await uploadFileToStorage(rgFront, `rg-front-${Date.now()}`);
      const rgBackUrl = await uploadFileToStorage(rgBack, `rg-back-${Date.now()}`);

      await createAppMutation.mutateAsync({
        jobId: parseInt(selectedJobId),
        fullName,
        phone,
        rgFrontUrl,
        rgBackUrl,
      });

      toast.success("Candidatura enviada com sucesso!");
      setSelectedJobId("");
      setFullName("");
      setPhone("");
      setRgFront(null);
      setRgBack(null);
      setRgFrontPreview("");
      setRgBackPreview("");
      setConsentimento(false);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Erro ao enviar candidatura. Tente novamente.");
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
      {/* Hero Section */}
      <section className="relative overflow-hidden px-4 py-20 sm:px-6 lg:px-8">
        <div className="mx-auto max-w-4xl text-center">
          <div className="mb-6 inline-flex items-center gap-2 rounded-full bg-blue-500/10 px-4 py-2 text-sm font-medium text-blue-400 border border-blue-500/20">
            <span className="flex h-2 w-2 rounded-full bg-blue-400"></span>
            100% HOME OFFICE
          </div>

          <h1 className="mb-6 text-5xl font-bold tracking-tight text-white sm:text-6xl">
            Trabalhe de Casa
            <span className="block bg-gradient-to-r from-blue-400 to-cyan-400 bg-clip-text text-transparent">
              Ganhe até R$ 12.000
            </span>
          </h1>

          <p className="mb-8 text-lg text-slate-300">
            🚀 Vagas exclusivas para trabalho remoto. Sem horário fixo, com treinamento completo incluso. Candidate-se agora!
          </p>

          <div className="grid grid-cols-1 gap-6 sm:grid-cols-3 mb-12">
            <div className="rounded-lg bg-slate-800/50 p-6 border border-slate-700">
              <div className="text-2xl font-bold text-blue-400">100%</div>
              <div className="text-sm text-slate-400">Remoto</div>
            </div>
            <div className="rounded-lg bg-slate-800/50 p-6 border border-slate-700">
              <div className="text-2xl font-bold text-cyan-400">R$ 12K</div>
              <div className="text-sm text-slate-400">Salário Mensal</div>
            </div>
            <div className="rounded-lg bg-slate-800/50 p-6 border border-slate-700">
              <div className="text-2xl font-bold text-purple-400">🎯</div>
              <div className="text-sm text-slate-400">Sem Horário Fixo</div>
            </div>
          </div>

          <Button
            asChild
            size="lg"
            className="bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white border-0"
          >
            <a href="#vagas">📝 Ver Vagas Disponíveis</a>
          </Button>
        </div>
      </section>

      {/* Featured Jobs Section */}
      <section id="vagas" className="px-4 py-20 sm:px-6 lg:px-8 bg-slate-800/50">
        <div className="mx-auto max-w-5xl">
          <div className="mb-12 text-center">
            <h2 className="mb-4 text-4xl font-bold text-white">💼 Vagas em Destaque</h2>
            <p className="text-slate-300">
              Escolha a vaga que mais combina com você e comece a trabalhar de casa
            </p>
          </div>

          {jobsQuery.isLoading ? (
            <div className="flex justify-center">
              <Loader2 className="h-8 w-8 animate-spin text-blue-400" />
            </div>
          ) : jobsQuery.data && jobsQuery.data.length > 0 ? (
            <div className="grid gap-6 md:grid-cols-2">
              {jobsQuery.data.map((job: any) => {
                const benefits = JSON.parse(job.benefits);
                return (
                  <Card
                    key={job.id}
                    className="bg-slate-800 border-slate-700 hover:border-blue-500/50 transition-all hover:shadow-lg hover:shadow-blue-500/10"
                  >
                    <div className="p-6">
                      <h3 className="mb-2 text-xl font-bold text-white">{job.title}</h3>
                      <div className="mb-4 inline-block rounded-full bg-pink-500/10 px-3 py-1 text-sm font-semibold text-pink-400">
                        💰 {job.salary}
                      </div>
                      <p className="mb-4 text-sm text-slate-300">{job.description}</p>
                      <div className="space-y-2">
                        {benefits.map((benefit: string, idx: number) => (
                          <div key={idx} className="flex items-center gap-2 text-sm text-slate-300">
                            <CheckCircle2 className="h-4 w-4 text-green-400" />
                            {benefit}
                          </div>
                        ))}
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          ) : (
            <div className="text-center text-slate-400">Nenhuma vaga disponível no momento.</div>
          )}
        </div>
      </section>

      {/* Application Form Section */}
      <section id="candidatura" className="px-4 py-20 sm:px-6 lg:px-8">
        <div className="mx-auto max-w-2xl">
          <div className="mb-12 text-center">
            <h2 className="mb-4 text-4xl font-bold text-white">📝 Candidate-se Agora</h2>
            <p className="text-slate-300">
              Preencha seus dados e anexe os documentos para iniciar o processo
            </p>
          </div>

          <Card className="bg-slate-800 border-slate-700">
            <form onSubmit={handleSubmit} className="space-y-6 p-8">
              {/* Job Selection */}
              <div>
                <Label htmlFor="vaga" className="text-white mb-2 block">
                  Selecione a Vaga <span className="text-red-400">*</span>
                </Label>
                <Select value={selectedJobId} onValueChange={setSelectedJobId}>
                  <SelectTrigger className="bg-slate-700 border-slate-600 text-white">
                    <SelectValue placeholder="-- Selecione uma vaga --" />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600">
                    {jobsQuery.data?.map((job: any) => (
                      <SelectItem key={job.id} value={job.id.toString()}>
                        {job.title} - {job.salary}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Full Name */}
              <div>
                <Label htmlFor="nome" className="text-white mb-2 block">
                  Nome Completo <span className="text-red-400">*</span>
                </Label>
                <Input
                  id="nome"
                  type="text"
                  placeholder="Ex: João Silva Santos"
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400"
                />
              </div>

              {/* Phone */}
              <div>
                <Label htmlFor="telefone" className="text-white mb-2 block">
                  Telefone com DDD <span className="text-red-400">*</span>
                </Label>
                <Input
                  id="telefone"
                  type="tel"
                  placeholder="Ex: (11) 99999-9999"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400"
                />
              </div>

              {/* RG Front */}
              <div>
                <Label className="text-white mb-3 block">
                  RG - Frente <span className="text-red-400">*</span>
                </Label>
                <div className="space-y-3">
                  <div className="flex gap-3">
                    <Button
                      type="button"
                      variant="outline"
                      className="flex-1 bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
                      onClick={() => document.getElementById("rgFrontInput")?.click()}
                    >
                      <Upload className="mr-2 h-4 w-4" />
                      📁 Escolher Arquivo
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      className="flex-1 bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
                      onClick={() => handleCameraCapture(false)}
                    >
                      <Camera className="mr-2 h-4 w-4" />
                      📷 Tirar Foto
                    </Button>
                  </div>
                  <input
                    id="rgFrontInput"
                    type="file"
                    accept="image/jpeg,image/png,application/pdf"
                    onChange={(e) => handleFileChange(e, false)}
                    className="hidden"
                  />
                  {rgFrontPreview && (
                    <div className="rounded-lg bg-slate-700 p-3">
                      <p className="text-sm text-green-400">✓ Arquivo selecionado</p>
                    </div>
                  )}
                  <p className="text-xs text-slate-400">
                    📎 Formatos: JPG, PNG ou PDF | Máx: 5MB
                  </p>
                </div>
              </div>

              {/* RG Back */}
              <div>
                <Label className="text-white mb-3 block">
                  RG - Verso <span className="text-red-400">*</span>
                </Label>
                <div className="space-y-3">
                  <div className="flex gap-3">
                    <Button
                      type="button"
                      variant="outline"
                      className="flex-1 bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
                      onClick={() => document.getElementById("rgBackInput")?.click()}
                    >
                      <Upload className="mr-2 h-4 w-4" />
                      📁 Escolher Arquivo
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      className="flex-1 bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
                      onClick={() => handleCameraCapture(true)}
                    >
                      <Camera className="mr-2 h-4 w-4" />
                      📷 Tirar Foto
                    </Button>
                  </div>
                  <input
                    id="rgBackInput"
                    type="file"
                    accept="image/jpeg,image/png,application/pdf"
                    onChange={(e) => handleFileChange(e, true)}
                    className="hidden"
                  />
                  {rgBackPreview && (
                    <div className="rounded-lg bg-slate-700 p-3">
                      <p className="text-sm text-green-400">✓ Arquivo selecionado</p>
                    </div>
                  )}
                  <p className="text-xs text-slate-400">
                    📎 Formatos: JPG, PNG ou PDF | Máx: 5MB
                  </p>
                </div>
              </div>

              {/* Consent */}
              <div className="flex items-start gap-3">
                <Checkbox
                  id="consentimento"
                  checked={consentimento}
                  onCheckedChange={(checked) => setConsentimento(checked as boolean)}
                  className="mt-1"
                />
                <Label htmlFor="consentimento" className="text-sm text-slate-300 cursor-pointer">
                  Concordo com a{" "}
                  <Link href="/privacy-policy" className="text-blue-400 hover:text-blue-300 underline">
                    Política de Privacidade
                  </Link>
                  <span className="text-red-400"> *</span>
                </Label>
              </div>

              {/* Submit Button */}
              <Button
                type="submit"
                disabled={isSubmitting}
                className="w-full bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white border-0 h-12 text-base font-semibold"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Enviando...
                  </>
                ) : (
                  "🚀 Enviar Candidatura"
                )}
              </Button>
            </form>
          </Card>
        </div>
      </section>

      {/* Footer */}
      <footer className="border-t border-slate-700 bg-slate-900 px-4 py-8 sm:px-6 lg:px-8">
        <div className="mx-auto max-w-5xl text-center text-sm text-slate-400">
          © 2024 Vagas Home Office - Todos os direitos reservados
        </div>
      </footer>
    </div>
  );
}
