/** @jsxImportSource react */
import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  Link,
  Svg,
  Path,
} from "@react-pdf/renderer";
import type { ResumeData } from "../types";

const styles = StyleSheet.create({
  page: {
    padding: 24,
    fontFamily: "Helvetica",
    fontSize: 8,
    lineHeight: 1.3,
    color: "#111827",
  },
  header: {
    marginBottom: 10,
    paddingBottom: 6,
    borderBottomWidth: 1,
    borderBottomColor: "#D1D5DB",
    alignItems: "center",
    flexDirection: "column",
    display: "flex",
  },
  name: {
    fontSize: 16,
    fontWeight: "bold",
    marginBottom: 6,
    textAlign: "center",
  },
  contactRow: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    flexWrap: "wrap",
    color: "#4B5563",
    fontSize: 8,
    marginTop: 2,
  },
  contactItem: {
    flexDirection: "row",
    alignItems: "center",
    marginHorizontal: 8,
    marginBottom: 2,
  },
  icon: {
    width: 9,
    height: 9,
    marginRight: 4,
  },
  section: {
    marginBottom: 8,
  },
  sectionTitle: {
    fontSize: 10,
    fontWeight: "bold",
    borderBottomWidth: 1,
    borderBottomColor: "#D1D5DB",
    marginBottom: 4,
    paddingBottom: 2,
  },
  columns: {
    flexDirection: "row",
  },
  column: {
    flex: 1,
    marginLeft: 8,
    marginRight: 8,
  },
  // Experience
  experienceItem: {
    marginBottom: 6,
    paddingLeft: 8,
    borderLeftWidth: 2,
    borderLeftColor: "#2563EB",
  },
  itemTitle: {
    fontSize: 9,
    fontWeight: "bold",
    marginBottom: 1,
  },
  itemSubtitle: {
    fontSize: 8,
    color: "#4B5563",
    marginBottom: 1,
  },
  list: {
    marginLeft: 8,
  },
  listItem: {
    flexDirection: "row",
    marginBottom: 1,
  },
  bullet: {
    width: 8,
    fontSize: 8,
    marginRight: 2,
  },
  listContent: {
    flex: 1,
    color: "#374151",
    fontSize: 8,
  },
  // Skills
  skillItem: {
    marginBottom: 2,
  },
  skillHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 1,
  },
  progressBarBg: {
    height: 4,
    backgroundColor: "#E5E7EB",
    borderRadius: 2,
  },
  progressBarFill: {
    height: 4,
    backgroundColor: "#2563EB",
    borderRadius: 2,
  },
  // Education
  educationItem: {
    marginBottom: 6,
    paddingLeft: 8,
    borderLeftWidth: 2,
    borderLeftColor: "#16A34A",
  },
  // Volunteer
  volunteerItem: {
    marginBottom: 4,
    paddingLeft: 8,
    borderLeftWidth: 2,
    borderLeftColor: "#9333EA",
  },
  // Awards
  awardItem: {
    marginBottom: 4,
    paddingLeft: 8,
    borderLeftWidth: 2,
    borderLeftColor: "#CA8A04",
  },
  summary: {
    marginBottom: 8,
    color: "#374151",
    fontSize: 8,
  },
});

const Icon = ({
  path,
  color = "currentColor",
}: {
  path: string;
  color?: string;
}) => (
  <Svg viewBox="0 0 24 24" style={styles.icon}>
    <Path d={path} fill={color} />
  </Svg>
);

const ExperienceSection = ({
  experience,
}: {
  experience: ResumeData["experience"];
}) => (
  <>
    {experience?.map((exp, i) => (
      <View key={i} style={styles.experienceItem}>
        <Text style={styles.itemTitle}>{exp.position}</Text>
        <Text style={styles.itemSubtitle}>
          {exp.company} • {exp.date} • {exp.location}
        </Text>
        <View style={styles.list}>
          {exp.description?.map((desc, j) => (
            <View key={j} style={styles.listItem}>
              <Text style={styles.bullet}>•</Text>
              <Text style={styles.listContent}>{desc}</Text>
            </View>
          ))}
        </View>
      </View>
    ))}
  </>
);

const SkillsSection = ({ skills }: { skills: ResumeData["skills"] }) => (
  <>
    {skills?.map((skill, i) => (
      <View key={i} style={styles.skillItem}>
        <View style={styles.skillHeader}>
          <Text style={{ fontSize: 8 }}>{skill.name}</Text>
          <Text style={{ color: "#4B5563", fontSize: 8 }}>{skill.level}/5</Text>
        </View>
        <View style={styles.progressBarBg}>
          <View
            style={[styles.progressBarFill, { width: `${skill.level * 20}%` }]}
          />
        </View>
      </View>
    ))}
  </>
);

const EducationSection = ({
  education,
}: {
  education: ResumeData["education"];
}) => (
  <>
    {education?.map((edu, i) => (
      <View key={i} style={styles.educationItem}>
        <Text style={styles.itemTitle}>{edu.institution}</Text>
        <Text style={styles.itemSubtitle}>
          {edu.degree} in {edu.field} • {edu.date}
        </Text>
        {edu.details && (
          <View style={styles.list}>
            {edu.details.map((detail, j) => (
              <View key={j} style={styles.listItem}>
                <Text style={styles.bullet}>•</Text>
                <Text style={styles.listContent}>{detail}</Text>
              </View>
            ))}
          </View>
        )}
      </View>
    ))}
  </>
);

const VolunteerSection = ({
  volunteer,
}: {
  volunteer: ResumeData["volunteer"];
}) => (
  <>
    {volunteer?.map((vol, i) => (
      <View key={i} style={styles.volunteerItem}>
        <Text style={styles.itemTitle}>{vol.organization}</Text>
        <Text style={styles.itemSubtitle}>
          {vol.position} • {vol.date}
        </Text>
      </View>
    ))}
  </>
);

const AwardsSection = ({ awards }: { awards: ResumeData["awards"] }) => (
  <>
    {awards?.map((award, i) => (
      <View key={i} style={styles.awardItem}>
        <Text style={styles.itemTitle}>{award.title}</Text>
        <Text style={styles.itemSubtitle}>
          {award.organization} • {award.date}
        </Text>
        {award.description && (
          <Text style={{ color: "#374151" }}>{award.description}</Text>
        )}
      </View>
    ))}
  </>
);

interface ResumeDocumentProps {
  data: ResumeData;
  resumeConfig: any;
  icons: { [key: string]: string };
}

export const ResumeDocument = ({
  data,
  resumeConfig,
  icons,
}: ResumeDocumentProps) => {
  const layout = data.layout
    ? {
        leftColumn: data.layout.left_column || [
          "experience",
          "volunteer",
          "awards",
        ],
        rightColumn: data.layout.right_column || ["skills", "education"],
      }
    : resumeConfig.layout || {
        leftColumn: ["experience", "volunteer", "awards"],
        rightColumn: ["skills", "education"],
      };

  const renderSectionContent = (sectionName: string) => {
    switch (sectionName) {
      case "experience":
        return <ExperienceSection experience={data.experience} />;
      case "skills":
        return <SkillsSection skills={data.skills} />;
      case "education":
        return <EducationSection education={data.education} />;
      case "volunteer":
        return <VolunteerSection volunteer={data.volunteer} />;
      case "awards":
        return <AwardsSection awards={data.awards} />;
      default:
        return null;
    }
  };

  const renderColumn = (sectionNames: string[]) => {
    return sectionNames.map((name) => {
      const config = resumeConfig.sections[name];
      const content = renderSectionContent(name);

      // Check if section has content (simple check)
      const hasContent =
        data[name as keyof ResumeData] &&
        (data[name as keyof ResumeData] as any[]).length > 0;

      if (!config || !hasContent || config.enabled === false) return null;

      return (
        <View key={name} style={styles.section}>
          <Text style={styles.sectionTitle}>{config.title}</Text>
          {content}
        </View>
      );
    });
  };

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.name}>{data.basics.name}</Text>
          <View style={styles.contactRow}>
            {data.basics.email && (
              <View style={styles.contactItem}>
                {icons["email"] && <Icon path={icons["email"]} />}
                <Text>{data.basics.email}</Text>
              </View>
            )}
            {data.basics.phone && (
              <View style={styles.contactItem}>
                {icons["phone"] && <Icon path={icons["phone"]} />}
                <Text>{data.basics.phone}</Text>
              </View>
            )}
            {data.basics.profiles?.map((profile: any, i: number) => (
              <View key={i} style={styles.contactItem}>
                {icons[profile.network.toLowerCase()] && (
                  <Icon path={icons[profile.network.toLowerCase()]} />
                )}
                <Link
                  src={profile.url}
                  style={{ color: "#4B5563", textDecoration: "none" }}
                >
                  {profile.url.replace(/^https?:\/\//, "").replace(/\/$/, "")}
                </Link>
              </View>
            ))}
          </View>
        </View>

        {/* Summary */}
        {data.summary && resumeConfig.sections.summary?.enabled !== false && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>
              {resumeConfig.sections.summary?.title || "Summary"}
            </Text>
            <Text style={styles.summary}>{data.summary.content}</Text>
          </View>
        )}

        {/* Columns */}
        <View style={styles.columns}>
          <View style={[styles.column, { marginLeft: 0, marginRight: 8 }]}>
            {renderColumn(layout.leftColumn)}
          </View>
          <View style={[styles.column, { marginLeft: 8, marginRight: 0 }]}>
            {renderColumn(layout.rightColumn)}
          </View>
        </View>
      </Page>
    </Document>
  );
};
