"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RichTextEditor } from "@/components/ui/rich-text-editor";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Loader2, ArrowLeft } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import Link from "next/link";
import { SearchableSelect } from "@/components/shared";
import { KENYA_COUNTIES, KENYA_CITIES } from "@/lib/kenya-locations";
import type { CompanyCategory } from "@/lib/types";

export default function CreateCompanyPage() {
  const router = useRouter();
  const [categories, setCategories] = useState<CompanyCategory[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [form, setForm] = useState({
    category_id: "",
    name: "",
    short_description: "",
    description: "",
    phone: "",
    email: "",
    website: "",
    address: "",
    city: "",
    county: "",
    meta_title: "",
    meta_description: "",
  });
  const [logo, setLogo] = useState<File | null>(null);
  const [coverImage, setCoverImage] = useState<File | null>(null);

  useEffect(() => {
    api.get("/api/companies/categories").then(({ data }) => setCategories(data.data));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const formData = new FormData();
      Object.entries(form).forEach(([key, value]) => {
        if (value) formData.append(key, value);
      });
      if (logo) formData.append("logo", logo);
      if (coverImage) formData.append("cover_image", coverImage);

      await api.post("/api/companies", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("Company created successfully");
      router.push("/dashboard/companies");
    } catch (err: any) {
      const message = err.response?.data?.message || "Failed to create company";
      toast.error(message);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" asChild>
          <Link href="/dashboard/companies">
            <ArrowLeft className="mr-2 h-4 w-4" /> Back
          </Link>
        </Button>
        <div>
          <h1 className="font-display text-2xl font-semibold">Add Company</h1>
          <p className="text-sm text-muted-foreground">Create a new company listing</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid gap-6 lg:grid-cols-3">
          {/* Main info */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle className="text-base">Company Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="name">Company Name *</Label>
                  <Input
                    id="name"
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: e.target.value })}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="category">Category *</Label>
                  <Select value={form.category_id} onValueChange={(v) => setForm({ ...form, category_id: v })}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select category" />
                    </SelectTrigger>
                    <SelectContent>
                      {categories.map((cat) => (
                        <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="short_desc">Short Description</Label>
                <Input
                  id="short_desc"
                  value={form.short_description}
                  onChange={(e) => setForm({ ...form, short_description: e.target.value })}
                  maxLength={500}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="desc">Full Description</Label>
                <RichTextEditor
                  content={form.description}
                  onChange={(html) => setForm({ ...form, description: html })}
                  placeholder="Describe the company..."
                />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="phone">Phone</Label>
                  <Input id="phone" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input id="email" type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="website">Website</Label>
                <Input id="website" value={form.website} onChange={(e) => setForm({ ...form, website: e.target.value })} placeholder="https://" />
              </div>
              <div className="space-y-2">
                <Label htmlFor="address">Address</Label>
                <Input id="address" value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label>City</Label>
                  <SearchableSelect
                    options={KENYA_CITIES}
                    value={form.city}
                    onChange={(v) => setForm({ ...form, city: v })}
                    placeholder="Select city"
                    searchPlaceholder="Search cities..."
                    allowCustom
                  />
                </div>
                <div className="space-y-2">
                  <Label>County</Label>
                  <SearchableSelect
                    options={KENYA_COUNTIES}
                    value={form.county}
                    onChange={(v) => setForm({ ...form, county: v })}
                    placeholder="Select county"
                    searchPlaceholder="Search counties..."
                    allowCustom
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Sidebar */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Media</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="logo">Logo</Label>
                  <Input id="logo" type="file" accept="image/*" onChange={(e) => setLogo(e.target.files?.[0] || null)} />
                  <p className="text-xs text-muted-foreground">Max 2MB. JPG, PNG or WebP.</p>
                  {logo && (
                    <div className="relative h-20 w-20 overflow-hidden rounded-md border">
                      <img src={URL.createObjectURL(logo)} alt="Logo preview" className="h-full w-full object-cover" />
                    </div>
                  )}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="cover">Cover Image</Label>
                  <Input id="cover" type="file" accept="image/*" onChange={(e) => setCoverImage(e.target.files?.[0] || null)} />
                  <p className="text-xs text-muted-foreground">Max 4MB. Recommended 1200×600.</p>
                  {coverImage && (
                    <div className="relative aspect-video w-full overflow-hidden rounded-md border">
                      <img src={URL.createObjectURL(coverImage)} alt="Cover preview" className="h-full w-full object-cover" />
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">SEO</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="meta_title">Meta Title</Label>
                  <Input
                    id="meta_title"
                    value={form.meta_title}
                    onChange={(e) => setForm({ ...form, meta_title: e.target.value })}
                    maxLength={70}
                  />
                  <p className="text-xs text-muted-foreground">{form.meta_title.length}/70</p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="meta_desc">Meta Description</Label>
                  <Textarea
                    id="meta_desc"
                    value={form.meta_description}
                    onChange={(e) => setForm({ ...form, meta_description: e.target.value })}
                    maxLength={160}
                    rows={3}
                  />
                  <p className="text-xs text-muted-foreground">{form.meta_description.length}/160</p>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <div className="flex justify-end gap-3">
          <Button variant="outline" asChild>
            <Link href="/dashboard/companies">Cancel</Link>
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Create Company
          </Button>
        </div>
      </form>
    </div>
  );
}
