"use client";

import { useState, useRef, useEffect } from "react";
import { 
  Building2, Image as ImageIcon, Globe, MapPin, 
  Phone, Mail, Settings as SettingsIcon, Save, Database, Shield,
  MailOpen, MessageCircle, Palette, FileText
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Switch } from "@/components/ui/switch";
import { toast } from "sonner";

export default function SettingsDashboard() {
  const [activeTab, setActiveTab] = useState("company");
  const [logoUrl, setLogoUrl] = useState<string | null>(null);
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoLightUrl, setLogoLightUrl] = useState<string | null>(null);
  const [logoLightFile, setLogoLightFile] = useState<File | null>(null);
  
  // Settings State
  const [name, setName] = useState("K CREATION ALGERIA");
  const [slogan, setSlogan] = useState("La Sécurité N'est Pas Un Hasard");
  const [description, setDescription] = useState("Leading manufacturer of industrial shredders and waste management solutions in Algeria.");
  const [address, setAddress] = useState("Zone Industrielle, Rouiba, Algiers");
  const [phone, setPhone] = useState("+213 550 00 00 00");
  const [email, setEmail] = useState("support@k-creation.dz");
  const [website, setWebsite] = useState("https://k-creation.com");
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const fileInputLightRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    fetch("/api/settings")
      .then(res => res.json())
      .then(data => {
        if (data.name) setName(data.name);
        if (data.slogan) setSlogan(data.slogan);
        if (data.description) setDescription(data.description);
        if (data.address) setAddress(data.address);
        if (data.phone) setPhone(data.phone);
        if (data.email) setEmail(data.email);
        if (data.website) setWebsite(data.website);
        if (data.logoUrl) setLogoUrl(data.logoUrl);
        if (data.logoLightUrl) setLogoLightUrl(data.logoLightUrl);
      })
      .catch(() => {}); // ignore fetch errors on mount
  }, []);

  const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setLogoFile(file);
      setLogoUrl(URL.createObjectURL(file));
      toast.success("Dark mode logo uploaded successfully!");
    }
  };

  const handleLogoLightUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setLogoLightFile(file);
      setLogoLightUrl(URL.createObjectURL(file));
      toast.success("Light mode logo uploaded successfully!");
    }
  };

  const handleSave = async () => {
    const formData = new FormData();
    formData.append("name", name);
    formData.append("slogan", slogan);
    formData.append("description", description);
    formData.append("address", address);
    formData.append("phone", phone);
    formData.append("email", email);
    formData.append("website", website);
    if (logoUrl) formData.append("logoUrl", logoUrl);
    if (logoFile) formData.append("logo", logoFile);
    if (logoLightUrl) formData.append("logoLightUrl", logoLightUrl);
    if (logoLightFile) formData.append("logoLight", logoLightFile);

    try {
      const res = await fetch("/api/settings", {
        method: "POST",
        body: formData
      });
      if (!res.ok) throw new Error("Failed to save settings");
      toast.success("Settings saved successfully!");
    } catch (error) {
      toast.error("Failed to save settings");
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-bold text-white tracking-tight">System Settings</h2>
          <p className="text-gray-400 mt-1">Configure company profiles, integrations, and application themes.</p>
        </div>
        <Button onClick={handleSave} className="bg-brand-red hover:bg-brand-red/90 text-white font-semibold">
          <Save className="w-4 h-4 mr-2" /> Save All Changes
        </Button>
      </div>

      <div className="flex flex-col md:flex-row gap-6">
        
        {/* Left Side Navigation */}
        <div className="w-full md:w-64 shrink-0">
          <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm p-2">
            <div className="space-y-1 flex flex-col">
              <Button 
                variant="ghost" 
                className={`justify-start ${activeTab === 'company' ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}
                onClick={() => setActiveTab('company')}
              >
                <Building2 className="w-4 h-4 mr-2" /> Company Profile
              </Button>
              <Button 
                variant="ghost" 
                className={`justify-start ${activeTab === 'business' ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}
                onClick={() => setActiveTab('business')}
              >
                <FileText className="w-4 h-4 mr-2" /> Business Legal Info
              </Button>
              <Button 
                variant="ghost" 
                className={`justify-start ${activeTab === 'integrations' ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}
                onClick={() => setActiveTab('integrations')}
              >
                <MessageCircle className="w-4 h-4 mr-2" /> API & Messaging
              </Button>
              <Button 
                variant="ghost" 
                className={`justify-start ${activeTab === 'theme' ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}
                onClick={() => setActiveTab('theme')}
              >
                <Palette className="w-4 h-4 mr-2" /> Theme Settings
              </Button>
            </div>
          </Card>
        </div>

        {/* Right Side Content */}
        <div className="flex-1">
          
          {/* COMPANY PROFILE */}
          {activeTab === 'company' && (
            <div className="space-y-6">
              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white">Brand Assets</CardTitle>
                  <CardDescription className="text-gray-400">Update company logo and public branding details.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="flex flex-col gap-6">
                    <div className="flex flex-col md:flex-row gap-6 items-center">
                      <input 
                        type="file" 
                        accept="image/*" 
                        className="hidden" 
                        ref={fileInputRef} 
                        onChange={handleLogoUpload} 
                      />
                      <div 
                        onClick={() => fileInputRef.current?.click()}
                        className="w-32 h-32 bg-black/40 border-2 border-dashed border-white/20 rounded-xl flex flex-col items-center justify-center text-gray-500 hover:text-white hover:border-brand-red cursor-pointer transition-colors overflow-hidden shrink-0"
                      >
                        {logoUrl ? (
                          <img src={logoUrl} alt="Dark Mode Logo" className="w-full h-full object-contain bg-black/40 p-2" />
                        ) : (
                          <>
                            <ImageIcon className="w-8 h-8 mb-2" />
                            <span className="text-xs text-center">Upload Logo<br/>(Dark Mode)</span>
                          </>
                        )}
                      </div>
                      
                      <input 
                        type="file" 
                        accept="image/*" 
                        className="hidden" 
                        ref={fileInputLightRef} 
                        onChange={handleLogoLightUpload} 
                      />
                      <div 
                        onClick={() => fileInputLightRef.current?.click()}
                        className="w-32 h-32 bg-white/10 border-2 border-dashed border-white/20 rounded-xl flex flex-col items-center justify-center text-gray-400 hover:text-white hover:border-brand-red cursor-pointer transition-colors overflow-hidden shrink-0"
                      >
                        {logoLightUrl ? (
                          <img src={logoLightUrl} alt="Light Mode Logo" className="w-full h-full object-contain bg-white/90 p-2" />
                        ) : (
                          <>
                            <ImageIcon className="w-8 h-8 mb-2" />
                            <span className="text-xs text-center">Upload Logo<br/>(Light Mode)</span>
                          </>
                        )}
                      </div>
                      
                      <div className="flex-1 w-full space-y-4">
                      <div className="space-y-2">
                        <Label className="text-gray-300">Company Name</Label>
                        <Input value={name} onChange={(e) => setName(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                      </div>
                      <div className="space-y-2">
                        <Label className="text-gray-300">Company Slogan</Label>
                        <Input value={slogan} onChange={(e) => setSlogan(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                      </div>
                    </div>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Company Description</Label>
                    <Textarea value={description} onChange={(e) => setDescription(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red resize-none h-24" />
                  </div>
                </CardContent>
              </Card>

              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white">Contact Information</CardTitle>
                </CardHeader>
                <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-gray-300">HQ Address</Label>
                    <Input value={address} onChange={(e) => setAddress(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Primary Phone</Label>
                    <Input value={phone} onChange={(e) => setPhone(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Support Email</Label>
                    <Input value={email} onChange={(e) => setEmail(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Website URL</Label>
                    <Input value={website} onChange={(e) => setWebsite(e.target.value)} className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* BUSINESS LEGAL INFO */}
          {activeTab === 'business' && (
            <div className="space-y-6">
              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white">Legal & Tax Information</CardTitle>
                  <CardDescription className="text-gray-400">These details will appear on official quotes and invoices.</CardDescription>
                </CardHeader>
                <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label className="text-gray-300">Registre de Commerce (RC)</Label>
                    <Input placeholder="Enter RC Number" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">NIF (Numéro d'Identification Fiscale)</Label>
                    <Input placeholder="Enter NIF" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">Article d'Imposition (AI)</Label>
                    <Input placeholder="Enter AI Number" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">VAT Number (NIS)</Label>
                    <Input placeholder="Enter NIS Number" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label className="text-gray-300">Primary Bank Account (RIB)</Label>
                    <Input placeholder="e.g. 000 00000 0000000000 00 BEA" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* INTEGRATIONS */}
          {activeTab === 'integrations' && (
            <div className="space-y-6">
              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white flex items-center gap-2"><MailOpen className="w-5 h-5 text-blue-400" /> SMTP Email Server</CardTitle>
                  <CardDescription className="text-gray-400">Configure email settings for sending invoices and marketing campaigns.</CardDescription>
                </CardHeader>
                <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-gray-300">SMTP Host</Label>
                    <Input placeholder="smtp.k-creation.dz" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">SMTP Port</Label>
                    <Input placeholder="587" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">SMTP User</Label>
                    <Input placeholder="no-reply@k-creation.dz" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">SMTP Password</Label>
                    <Input type="password" placeholder="••••••••" className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                </CardContent>
              </Card>

              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white flex items-center gap-2"><MessageCircle className="w-5 h-5 text-emerald-500" /> WhatsApp Cloud API</CardTitle>
                  <CardDescription className="text-gray-400">Connect your WhatsApp Business account for direct messaging.</CardDescription>
                </CardHeader>
                <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label className="text-gray-300">Business Phone Number</Label>
                    <Input placeholder="+213 550..." className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-gray-300">API Access Token</Label>
                    <Input type="password" placeholder="EAAI..." className="bg-black/40 border-white/10 text-white focus-visible:ring-brand-red" />
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* THEME */}
          {activeTab === 'theme' && (
            <div className="space-y-6">
              <Card className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
                <CardHeader>
                  <CardTitle className="text-white">Platform Theme</CardTitle>
                  <CardDescription className="text-gray-400">Customize the look and feel of the ERP portal.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="flex items-center justify-between p-4 bg-black/40 border border-white/10 rounded-lg">
                    <div>
                      <h4 className="text-white font-medium">Dark Mode</h4>
                      <p className="text-sm text-gray-500">Enable premium dark industrial theme.</p>
                    </div>
                    <Switch defaultChecked />
                  </div>
                  
                  <div>
                    <h4 className="text-white font-medium mb-3">Primary Accent Color</h4>
                    <div className="flex gap-4">
                      <div className="w-10 h-10 rounded-full bg-[#D80B17] ring-2 ring-white cursor-pointer"></div>
                      <div className="w-10 h-10 rounded-full bg-blue-600 opacity-50 cursor-pointer hover:opacity-100 transition-opacity"></div>
                      <div className="w-10 h-10 rounded-full bg-emerald-600 opacity-50 cursor-pointer hover:opacity-100 transition-opacity"></div>
                      <div className="w-10 h-10 rounded-full bg-purple-600 opacity-50 cursor-pointer hover:opacity-100 transition-opacity"></div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
