"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import {
    ArrowLeft,
    Building2,
    Globe,
    MapPin,
    DollarSign,
    Users,
    Briefcase,
    TrendingUp,
    Save,
    X,
    Hash,
    Calendar,
    Phone,
    Mail,
    Plus,
    Trash2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { ReactSelect } from "@/components/ui/react-select"
import { toast } from "sonner"
import { cn } from "@/lib/utils"
import { Card } from "@/components/ui/card"

const INDUSTRIES = ['MarTech', 'SaaS', 'E-Commerce', 'FMCG', 'Real Estate', 'Finance', 'Logistics', 'Media', 'EdTech', 'HealthTech']
const SIZES = ['Startup', 'SME', 'Enterprise']
const STAGES = ['Prospecting', 'Qualified', 'Proposal Sent', 'Negotiation', 'Closed Won']

const INDUSTRY_OPTIONS = INDUSTRIES.map((i) => ({ value: i, label: i }))
const SIZE_OPTIONS = SIZES.map((s) => ({ value: s, label: s }))
const STAGE_OPTIONS = STAGES.map((s) => ({ value: s, label: s }))
const ASSIGNED_REP_OPTIONS = [
    { value: "zara", label: "Zara Ahmed (Team Alpha)" },
    { value: "omar", label: "Omar Farooq (Team Alpha)" },
    { value: "sana", label: "Sana Malik (Team Beta)" },
    { value: "bilal", label: "Bilal Khan (Team Beta)" },
    { value: "hira", label: "Hira Qureshi (Team Gamma)" },
    { value: "tariq", label: "Tariq Rauf (Team Gamma)" },
]

export default function AddCompanyPage() {
    const router = useRouter()
    const [loading, setLoading] = React.useState(false)
    const [contacts, setContacts] = React.useState([{ name: "", title: "" }])
    const [industry, setIndustry] = React.useState("SaaS")
    const [companySize, setCompanySize] = React.useState("SME")
    const [dealStage, setDealStage] = React.useState("Prospecting")
    const [assignedRep, setAssignedRep] = React.useState("zara")

    const addContact = () => setContacts([...contacts, { name: "", title: "" }])
    const removeContact = (i: number) => setContacts(contacts.filter((_, idx) => idx !== i))
    const updateContact = (i: number, field: 'name' | 'title', val: string) => {
        setContacts(contacts.map((c, idx) => idx === i ? { ...c, [field]: val } : c))
    }

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
            toast.success("Company created successfully!")
            router.push("/companies")
        }, 1200)
    }

    return (
        <div className="flex flex-col h-full gap-6 p-2 md:p-6 animate-in fade-in slide-in-from-bottom-4 duration-500 overflow-y-auto scrollbar-themed">
            {/* Header */}
            <div className="flex items-center justify-between border-b border-border/60 pb-6">
                <div className="flex items-center gap-4">
                    <Button
                        variant="ghostBackCircle"
                        onClick={() => router.back()}
                    >
                        <ArrowLeft size={20} />
                    </Button>
                    <div className="flex flex-col">
                        <h1 className="text-[21px] font-extrabold text-text font-['Lexend'] tracking-tight">Add New Company</h1>
                        <p className="text-[12px] text-gray-700 font-normal mt-0.5">Register a new account and link it to your CRM pipeline.</p>
                    </div>
                </div>
            </div>

            <form onSubmit={handleSubmit} className="flex flex-col gap-6">
                <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">

                    {/* Company Identity */}
                    <Card className="gap-0 p-6">
                        <div className="flex items-center gap-2 pb-2 mb-5 border-b border-white/60">
                            <div className="size-8 rounded-lg bg-accent/10 flex items-center justify-center text-accent">
                                <Building2 size={16} />
                            </div>
                            <h2 className="text-[15px] font-bold text-text font-['Lexend']">Company Identity</h2>
                        </div>

                        <div className="flex flex-col gap-2">
                            <Label htmlFor="company-name" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Company Name *</Label>
                            <Input id="company-name" placeholder="e.g. Nexus Solutions" required className="bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                                <Label className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Industry</Label>
                                <ReactSelect
                                    value={industry}
                                    onValueChange={setIndustry}
                                    options={INDUSTRY_OPTIONS}
                                    placeholder="Select industry"
                                    triggerClassName="h-11 min-h-11 rounded-xl bg-bg/50 border-border"
                                    contentClassName="rounded-xl"
                                />
                            </div>
                            <div className="flex flex-col gap-2">
                                <Label className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Company Size</Label>
                                <ReactSelect
                                    value={companySize}
                                    onValueChange={setCompanySize}
                                    options={SIZE_OPTIONS}
                                    placeholder="Select size"
                                    triggerClassName="h-11 min-h-11 rounded-xl bg-bg/50 border-border"
                                    contentClassName="rounded-xl"
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="employees" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Employees</Label>
                                <div className="relative">
                                    <Users size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="employees" type="number" placeholder="e.g. 120" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="founded" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Founded Year</Label>
                                <div className="relative">
                                    <Calendar size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="founded" type="number" placeholder="e.g. 2015" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                        </div>
                    </Card>

                    {/* Contact & Online Presence */}
                    <Card className="gap-0 p-6">
                        <div className="flex items-center gap-2 pb-2 mb-5 border-b border-white/60">
                            <div className="size-8 rounded-lg bg-blue-500/10 flex items-center justify-center text-blue-600">
                                <Globe size={16} />
                            </div>
                            <h2 className="text-[15px] font-bold text-text font-['Lexend']">Contact & Online Presence</h2>
                        </div>

                        <div className="flex flex-col gap-2">
                            <Label htmlFor="website" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Website URL</Label>
                            <div className="relative">
                                <Globe size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                <Input id="website" placeholder="https://company.com" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="email" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Business Email</Label>
                                <div className="relative">
                                    <Mail size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="email" type="email" placeholder="info@company.com" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="phone" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Phone Number</Label>
                                <div className="relative">
                                    <Phone size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="phone" placeholder="+92 21 1234567" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="city" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">City</Label>
                                <div className="relative">
                                    <MapPin size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="city" placeholder="e.g. Karachi" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="country" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Country</Label>
                                <Input id="country" placeholder="e.g. Pakistan" defaultValue="Pakistan" className="bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                            </div>
                        </div>
                    </Card>

                    {/* Sales Pipeline */}
                    <Card className="gap-0 p-6">
                        <div className="flex items-center gap-2 pb-2 mb-5 border-b border-white/60">
                            <div className="size-8 rounded-lg bg-green-500/10 flex items-center justify-center text-green-600">
                                <TrendingUp size={16} />
                            </div>
                            <h2 className="text-[15px] font-bold text-text font-['Lexend']">Sales Pipeline</h2>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="flex flex-col gap-2">
                                <Label className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Deal Stage</Label>
                                <ReactSelect
                                    value={dealStage}
                                    onValueChange={setDealStage}
                                    options={STAGE_OPTIONS}
                                    triggerClassName="h-11 min-h-11 rounded-xl bg-bg/50 border-border"
                                    contentClassName="rounded-xl"
                                />
                            </div>
                            <div className="flex flex-col gap-2">
                                <Label htmlFor="annual-revenue" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Annual Revenue</Label>
                                <div className="relative">
                                    <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                    <Input id="annual-revenue" placeholder="e.g. 2.5M" className="pl-9 bg-bg/50 border-border focus:border-accent rounded-xl h-11" />
                                </div>
                            </div>
                        </div>

                        <div className="flex flex-col gap-2">
                            <Label className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Assigned Sales Rep</Label>
                            <ReactSelect
                                value={assignedRep}
                                onValueChange={setAssignedRep}
                                options={ASSIGNED_REP_OPTIONS}
                                triggerClassName="h-11 min-h-11 rounded-xl bg-bg/50 border-border"
                                contentClassName="rounded-xl"
                            />
                        </div>

                        <div className="flex flex-col gap-2">
                            <Label htmlFor="notes" className="text-[11px] font-bold uppercase tracking-widest text-gray-600 ml-1">Internal Notes</Label>
                            <textarea
                                id="notes"
                                placeholder="Any background, special requirements, or notes about this company..."
                                className="w-full p-4 bg-bg/50 border border-border rounded-2xl text-[13px] font-normal outline-none focus:border-accent transition-all resize-none min-h-[90px]"
                            />
                        </div>
                    </Card>

                    {/* Key Contacts */}
                    <Card className="gap-0 p-6">
                        <div className="flex items-center justify-between pb-2 mb-5 border-b border-white/60">
                            <div className="flex items-center gap-2">
                                <div className="size-8 rounded-lg bg-orange-500/10 flex items-center justify-center text-orange-600">
                                    <Briefcase size={16} />
                                </div>
                                <h2 className="text-[15px] font-bold text-text font-['Lexend']">Key Contacts</h2>
                            </div>
                            <Button type="button" variant="ghostAccent" size="sm" onClick={addContact}>
                                <Plus size={14} /> Add Row
                            </Button>
                        </div>

                        <div className="flex flex-col gap-3">
                            {contacts.map((contact, idx) => (
                                <div key={idx} className="flex items-center gap-3 group">
                                    <div className="size-7 rounded-full bg-bg border border-border flex items-center justify-center text-[11px] font-bold text-gray-500 shrink-0">
                                        {idx + 1}
                                    </div>
                                    <Input
                                        value={contact.name}
                                        onChange={e => updateContact(idx, 'name', e.target.value)}
                                        placeholder="Contact Name"
                                        className="bg-bg/50 border-border focus:border-accent rounded-xl h-10 flex-1"
                                    />
                                    <Input
                                        value={contact.title}
                                        onChange={e => updateContact(idx, 'title', e.target.value)}
                                        placeholder="Job Title"
                                        className="bg-bg/50 border-border focus:border-accent rounded-xl h-10 flex-1"
                                    />
                                    {contacts.length > 1 && (
                                        <Button
                                            type="button"
                                            variant="ghostIconRowDangerReveal"
                                            onClick={() => removeContact(idx)}
                                        >
                                            <Trash2 size={14} />
                                        </Button>
                                    )}
                                </div>
                            ))}
                        </div>

                        <p className="text-[11px] text-gray-500 bg-bg/50 border border-border/40 rounded-xl px-4 py-2.5">
                            💡 Add the primary stakeholders who will be involved in the deal. These will appear on the company detail panel.
                        </p>
                    </Card>
                </div>

                {/* Form Actions */}
                <div className="flex items-center justify-end gap-3 pb-10">
                    <Button
                        type="button"
                        variant="outlineGlassBack"
                        onClick={() => router.back()}
                    >
                        <X size={16} className="mr-2" /> Cancel
                    </Button>
                    <Button
                        type="submit"
                        variant="accentHeroSubmit"
                        disabled={loading}
                    >
                        {loading ? (
                            <div className="flex items-center gap-2">
                                <div className="h-4 w-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                                <span>Creating...</span>
                            </div>
                        ) : (
                            <div className="flex items-center gap-2">
                                <Save size={16} />
                                <span>Create Company</span>
                            </div>
                        )}
                    </Button>
                </div>
            </form>
        </div>
    )
}
