"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ASSET_TYPES, MARKETS } from "@/lib/utils";
import { Loader2 } from "lucide-react";

export function BuyerForm({ onSuccess }: { onSuccess?: () => void }) {
  const [loading, setLoading] = useState(false);
  const [selectedAssetTypes, setSelectedAssetTypes] = useState<string[]>([]);
  const [selectedLocations, setSelectedLocations] = useState<string[]>([]);
  const [formData, setFormData] = useState({
    name: "",
    company: "",
    email: "",
    phone: "",
    price_min: "",
    price_max: "",
    cap_rate_min: "",
    cap_rate_max: "",
    preferences: "",
  });

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const toggleAssetType = (type: string) => {
    setSelectedAssetTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type]
    );
  };

  const toggleLocation = (loc: string) => {
    setSelectedLocations((prev) =>
      prev.includes(loc) ? prev.filter((l) => l !== loc) : [...prev, loc]
    );
  };

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

    try {
      const res = await fetch('/api/buyers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.name,
          company: formData.company || null,
          email: formData.email,
          phone: formData.phone || null,
          asset_types: selectedAssetTypes,
          target_locations: selectedLocations,
          price_min: formData.price_min ? parseFloat(formData.price_min) : null,
          price_max: formData.price_max ? parseFloat(formData.price_max) : null,
          cap_rate_min: formData.cap_rate_min ? parseFloat(formData.cap_rate_min) : null,
          cap_rate_max: formData.cap_rate_max ? parseFloat(formData.cap_rate_max) : null,
          preferences: formData.preferences || null,
        }),
      });

      if (res.ok) {
        alert("Buyer added successfully!");
        onSuccess?.();
      } else {
        const err = await res.json();
        alert(err.error || "Failed to add buyer.");
      }
    } catch {
      alert("Failed to add buyer. Please try again.");
    }

    setLoading(false);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Contact Information</CardTitle>
          <CardDescription>Basic buyer contact details</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="buyer-name">Full Name *</Label>
              <Input
                id="buyer-name"
                placeholder="John Smith"
                value={formData.name}
                onChange={(e) => handleChange("name", e.target.value)}
                required
                className="mt-1.5"
              />
            </div>
            <div>
              <Label htmlFor="buyer-company">Company</Label>
              <Input
                id="buyer-company"
                placeholder="Smith Capital Group"
                value={formData.company}
                onChange={(e) => handleChange("company", e.target.value)}
                className="mt-1.5"
              />
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="buyer-email">Email *</Label>
              <Input
                id="buyer-email"
                type="email"
                placeholder="john@smithcapital.com"
                value={formData.email}
                onChange={(e) => handleChange("email", e.target.value)}
                required
                className="mt-1.5"
              />
            </div>
            <div>
              <Label htmlFor="buyer-phone">Phone</Label>
              <Input
                id="buyer-phone"
                type="tel"
                placeholder="(555) 123-4567"
                value={formData.phone}
                onChange={(e) => handleChange("phone", e.target.value)}
                className="mt-1.5"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Acquisition Criteria</CardTitle>
          <CardDescription>What is this buyer looking for?</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Asset Types */}
          <div>
            <Label>Target Asset Types</Label>
            <div className="flex flex-wrap gap-2 mt-1.5">
              {ASSET_TYPES.map((type) => (
                <button
                  key={type}
                  type="button"
                  onClick={() => toggleAssetType(type)}
                  className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
                    selectedAssetTypes.includes(type)
                      ? "bg-navy-800 text-white border-navy-800"
                      : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"
                  }`}
                >
                  {type}
                </button>
              ))}
            </div>
          </div>

          {/* Target Locations */}
          <div>
            <Label>Target Locations</Label>
            <div className="flex flex-wrap gap-2 mt-1.5 max-h-32 overflow-y-auto">
              {MARKETS.map((loc) => (
                <button
                  key={loc}
                  type="button"
                  onClick={() => toggleLocation(loc)}
                  className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
                    selectedLocations.includes(loc)
                      ? "bg-navy-800 text-white border-navy-800"
                      : "bg-white text-navy-600 border-navy-200 hover:border-navy-400"
                  }`}
                >
                  {loc}
                </button>
              ))}
            </div>
          </div>

          {/* Price Range */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="price_min">Min Price ($)</Label>
              <Input
                id="price_min"
                type="number"
                placeholder="1,000,000"
                value={formData.price_min}
                onChange={(e) => handleChange("price_min", e.target.value)}
                className="mt-1.5"
              />
            </div>
            <div>
              <Label htmlFor="price_max">Max Price ($)</Label>
              <Input
                id="price_max"
                type="number"
                placeholder="10,000,000"
                value={formData.price_max}
                onChange={(e) => handleChange("price_max", e.target.value)}
                className="mt-1.5"
              />
            </div>
          </div>

          {/* Cap Rate Range */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="cap_rate_min">Min Cap Rate (%)</Label>
              <Input
                id="cap_rate_min"
                type="number"
                step="0.01"
                placeholder="5.00"
                value={formData.cap_rate_min}
                onChange={(e) => handleChange("cap_rate_min", e.target.value)}
                className="mt-1.5"
              />
            </div>
            <div>
              <Label htmlFor="cap_rate_max">Max Cap Rate (%)</Label>
              <Input
                id="cap_rate_max"
                type="number"
                step="0.01"
                placeholder="8.00"
                value={formData.cap_rate_max}
                onChange={(e) => handleChange("cap_rate_max", e.target.value)}
                className="mt-1.5"
              />
            </div>
          </div>

          {/* Preferences */}
          <div>
            <Label htmlFor="preferences">Additional Preferences</Label>
            <Textarea
              id="preferences"
              placeholder="Value-add opportunities, 1031 exchange buyer, looking for NNN leases..."
              value={formData.preferences}
              onChange={(e) => handleChange("preferences", e.target.value)}
              rows={3}
              className="mt-1.5"
            />
          </div>
        </CardContent>
      </Card>

      <Button type="submit" variant="gold" className="w-full" size="lg" disabled={loading}>
        {loading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            Adding Buyer...
          </>
        ) : (
          "Add Buyer"
        )}
      </Button>
    </form>
  );
}
